You are on page 1of 4

// Template in C++

#include <iostream>

using namespace std;

template <class T>

class myclass{

public:

T *arr;

int size;

myclass(int s){

size =s;

arr = new T[size];

T display(myclass &mc){

int res =0;

for(int i=0; i<5; i++){

res+= this->arr[i]*mc.arr[i];

return res;

};

int main() {

myclass <int> obj1(5);

obj1.arr[0] =2;

obj1.arr[1] =5;

obj1.arr[2] =6;
obj1.arr[3] =7;

obj1.arr[4] =8;

myclass <int> obj2(5);

obj2.arr[0] =2;

obj2.arr[1] =5;

obj2.arr[2] =6;

obj2.arr[3] =7;

obj2.arr[4] =8;

int a = obj1.display(obj2);

cout<<a;

// Template with multiple parameters

#include <iostream>

using namespace std;

template <class t1, class t2>

class myclass{

t1 d1;

t2 d2;

public:

myclass(t1 a, t2 b){

d1 =a;

d2 = b;
}

void display(){

cout <<this->d1 << " " << this->d2;

};

int main() {

myclass <int, char> obj(10, 'A');

obj.display();

// Template with default parameters

#include <iostream>

using namespace std;

template <class t1 = int, class t2 = float, class t3 = char>

class myclass{

t1 d1;

t2 d2;

t3 d3;

public:

myclass(t1 a, t2 b, t3 c){

d1=a;
d2=b;

d3=c;

void display(){

cout <<"Value of d1 is " << d1 <<endl;

cout <<"Value of d2 is " << d2 <<endl;

cout <<"Value of d3 is " << d3 <<endl;

};

int main() {

myclass <> obj1(1, 4.98,'x');

obj1.display();

cout <<"___________________________" <<endl;;

myclass <char, float, int> obj2('q', 3.5, 4);

obj2.display();

You might also like