Class Templates

Generic classes

Interview Relevant: STL foundation

Class Templates

Create classes that work with any type.

Code Examples

Class templates for reusable data structures.

cpp
1template<typename T>
2class Stack {
3    vector<T> elements;
4
5public:
6    void push(const T& elem) {
7        elements.push_back(elem);
8    }
9
10    T pop() {
11        T top = elements.back();
12        elements.pop_back();
13        return top;
14    }
15
16    bool empty() const {
17        return elements.empty();
18    }
19};
20
21// Usage
22Stack<int> intStack;
23intStack.push(42);
24
25Stack<string> stringStack;
26stringStack.push("hello");
27
28// Template with default type
29template<typename T = int>
30class Counter {
31    T value = T{};
32};
33Counter<> c1;        // Uses default (int)
34Counter<double> c2;  // Uses double

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In