Template Class Example in C++


In the code, a class template stack is defined which is used to create stack objects of any type T. The class has two private data members stk which is a pointer to an array of type T and top which keeps track of the top element of the stack. The class also has a public constructor which initializes the size of the stack, a push method to insert elements into the stack, and a pop method to remove elements from the stack.

In the main function, a stack object s of type int is created with a size of 2. Two integers 10 and 12 are pushed onto the stack using the push method. However, when the push method is called again with the argument 15, the stack is full and the message "Stack Full" is printed on the console.

Note that the implementation of the pop method is incomplete and may cause undefined behavior when called on an empty stack. It is recommended to add a check for an empty stack before popping an element from it.

Source Code

#include<iostream>
using namespace std;
template <class T>
class stack
{
    T *stk;
    int top;
    int nSize;
public:
    stack(int sz)
    {
        nSize=sz;
        top=-1;
        stk=new T[nSize];
    }
    void push(T x);
    T pop();
};
template <class T>
void stack<T>::push(T x)
{
    if(top==nSize-1)
        cout<<"Stack Full"<<endl;
    else
    {
        top++;
        stk[top]=x;
    }
}
template <class T>
T stack<T>::pop()
{
    T x=0;
    if(top==-1)
        cout<<"Stack Empty "<<endl;
    else
    {
       x=stk[top] ;
       top--;
    }
    return x;
}
int main()
{
    stack<int> s(2);
    s.push(10);
    s.push(12);
    s.push(15);
    return 0;
}
To download raw file Click Here

Output

Stack Full

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples