Here is an example program to illustrate the class template.
//implement stack class as a template #include<iostream> using namespace std; const int MAX =100; //size of array template <class Type> class Stack { private: Type st[MAX]; int top; public: Stack() { top=-1; } void push(Type var) { st[++top]=var; } Type pop() { return st[top--]; } int size() { return (top+1); } }; int main() { Stack<float> s1; s1.push(12.3435); s1.push(2222.2F); s1.push(1111.1F); cout<<"\nSize of stack: "<<s1.size(); cout<<"\nNumber popped: "<<s1.pop(); s1.push(13432); cout<<"\nSize of stack: "<<s1.size(); cout<<"\nNumber popped: "<<s1.pop(); Stack<int>s2; cout<<"\nSize of stack: "<<s2.size(); s2.push(33); s2.push(343); s2.push(54); cout<<"\nSize of stack: "<<s2.size(); cout<<"\nNumber popped: "<<s2.pop(); cout<<"\nNumber popped: "<<s2.pop(); cout<<"\nSize of stack: "<<s2.size(); Stack <char> s3; cout<<"\nSize of stack: "<<s3.size(); s3.push('a'); s3.push('A'); s3.push('B'); cout<<"\nSize of stack: "<<s3.size(); cout<<"\nCharacter popped: "<<s3.pop(); cout<<"\nSize of stack: "<<s3.size(); return 0; }
The output of the program is:
Size of stack: 3 Number popped: 1111.1 Size of stack: 4 Number popped: 13432 Size of stack: 0 Size of stack: 3 Number popped: 54 Number popped: 343 Size of stack: 1 Size of stack: 0 Size of stack: 3 Character popped: C Size of stack: 2