C++ Class Template Example

5 min read Jul 01, 2024
C++ Class Template Example

C++ Class Template Example: A Comprehensive Guide

Class templates in C++ are powerful tools that allow you to create generic classes that can work with different data types. This means you can write a single class definition that can handle integers, floats, strings, or any other data type you need.

Here's a step-by-step guide to understanding and using C++ class templates with a practical example:

Understanding Class Templates

  • Generic Programming: Templates enable generic programming, meaning you write code once that works with various data types without re-implementing for each type.
  • Flexibility and Reusability: Class templates promote code reusability, minimizing redundancy and making your code more flexible.
  • Syntax: The template keyword followed by angle brackets (<T> where T is a placeholder for the data type) is used to define a class template.

A Simple Example: A Generic Stack

#include 

template  // Declaring a template with 'T' as the data type placeholder
class Stack {
private:
    T* data;  // Array to store elements
    int top;  // Index of the top element
    int capacity; // Maximum capacity of the stack

public:
    Stack(int size) : top(-1), capacity(size) {
        data = new T[capacity];
    }

    ~Stack() {
        delete[] data;
    }

    void push(const T& value) {
        if (top == capacity - 1) {
            std::cerr << "Stack overflow!\n";
            return;
        }
        data[++top] = value;
    }

    T pop() {
        if (top == -1) {
            std::cerr << "Stack underflow!\n";
            return T(); // Returning a default value for the type
        }
        return data[top--];
    }

    T peek() {
        if (top == -1) {
            std::cerr << "Stack is empty!\n";
            return T(); // Returning a default value for the type
        }
        return data[top];
    }

    bool isEmpty() {
        return top == -1;
    }
};

int main() {
    Stack intStack(5); // Creating a stack of integers
    intStack.push(10);
    intStack.push(20);
    std::cout << "Popped element: " << intStack.pop() << std::endl;

    Stack stringStack(3); // Creating a stack of strings
    stringStack.push("Hello");
    stringStack.push("World");
    std::cout << "Peeked element: " << stringStack.peek() << std::endl;

    return 0;
}

Explanation:

  1. Template Declaration: The template <typename T> line declares a class template called Stack. The T placeholder will be replaced with the actual data type at instantiation.
  2. Data Members: data, top, and capacity are defined to store the stack elements, track the top element's index, and manage the stack's capacity. Notice that data is declared as a pointer to the type T, allowing for dynamic memory allocation.
  3. Constructor: The constructor initializes top, capacity, and dynamically allocates memory for the data array.
  4. Destructor: The destructor releases the memory allocated for data to avoid memory leaks.
  5. Methods: push, pop, peek, and isEmpty define the typical stack operations. Note that the methods work with T, ensuring they operate correctly with any data type used with the Stack template.

Conclusion

C++ class templates are a powerful feature that promotes code reuse and flexibility. Understanding how to create and use them opens up possibilities for designing generic data structures and algorithms that can work with various data types. By applying the principles illustrated in this guide, you can start leveraging the benefits of class templates in your C++ projects.