Template Class Example in C++


Description:

A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.

Example Program:

Here is the simple program template class in C++.

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(3);
    s.push(10);
    s.push(12);
    s.push(15);
    return 0;
}
To download raw file Click Here


Basic Programs


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


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples



Learn All in Tamil © Designed & Developed By Tutor Joes