Class template
In addition to function template C++ also supports the concept of class template
“A class template is a class definition that describes a family of related classes.”
Question:1
C++ program using class templates to take input for two numbers calculate and display their sum , the number may be an int, float, or double.
Sol:
#include<iostream> #include<conio.h> using namespace std; template<class T> class sample { private: T n1,n2,n3; public: void get(); void disp(); void cal(); }; template<class T> void sample<T>::get() { cout<<"Enter 2 numbers "; cin>>n1>>n2; } template<class T> void sample<T>::cal() { n3=n1+n2; } template<class T> void sample<T>::disp() { cal(); cout<<"sum is "<<n3<<endl; } int main() { //clrscr(); sample <int> s1; sample <float> s2; cout<<"for int values"<<endl; s1.get();s1.disp(); cout<<"for float values"<<endl; s2.get();s2.disp(); getch(); return(0); }