Skip to main content

Class template with suitable example

Short answer

A class template defines a generic class with type parameter. For example, a Stack template<class T> stores an array of T and push/pop return T. Objects are Stack<int> and Stack<char>. This one class works for any type, avoiding code duplication. The compiler instantiates a separate class for each T used.

Explain class template with suitable example.

A class template is a blueprint for a generic class; data members, function arguments and return types can use a type parameter. The compiler creates a real class for each type used, so one class works for int, float, char and so on.

Syntax:

template <class T>
class ClassName {
    // members using T
};
ClassName<int> obj;      // instantiation

Example: generic Stack

#include <iostream>
using namespace std;

template <class T>
class Stack {
    T arr[10];
    int top;
public:
    Stack() { top = -1; }
    void push(T x) {
        if (top == 9) cout << "Stack full\n";
        else arr[++top] = x;
    }
    T pop() {
        if (top == -1) { cout << "Stack empty\n"; return T(); }
        return arr[top--];
    }
};

int main() {
    Stack<int> s1;
    s1.push(10); s1.push(20);
    cout << s1.pop() << endl;        // 20

    Stack<char> s2;
    s2.push('A'); s2.push('B');
    cout << s2.pop() << endl;        // B
    return 0;
}

The same Stack code is used once for integers and once for characters, avoiding two separate classes.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 9 questions →