Template class : Write a template class and add two number. Test integer and double type value inside main.

 

Template class : Write a template class and add two number. Test integer and double type value inside main.

  • define Template
  • define class
  • variable should be Template type
  • add two number 
  • test inside main
#include<iostream>
using namespace std;
template<class T> // template definition
class Add // class starts
{
private:
T a;// variable which is type T
T b;//
public:
Add(T a,T b)// define value
{
this ->a=a;
this ->b=b;
}
T sum()// function which return sum of type T
{
return(a+b);
}
};
int main()
{
Add<int>a(1,2);// supply int type value
cout<<"Sum of integer number :"<<a.sum()<<endl;
Add <double>b(1.2,2.3);//supply double type value
cout<<"Sum of double number :"<<b.sum()<<endl;
return 0;
}
view raw .cc hosted with ❤ by GitHub
Sum of integer number :3 
Sum of double number :3.5

0 Comments