Easy C++


C++ Tutorial - Lesson 35: Class Templates


by John Kopp

Support this site at no cost to you

Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. This lesson is an introduction to class templates. Class templates are an advanced topic that we will study in more detail in the lessons in Topics in C++. Class templates provide a way to parameterize the types within a class. This means that rather than explicitly specifying the data type associated with a class member or method, a placeholder is used. When we instantiate an instance of the class, the actual data type is substituted for the parameter, or placeholder. The process of forming a class with specific data types from a class template is called template instantiation.

In addition to parameterizing types, it is possible to use non-type parameters in a class template. These non-type parameters will serve as constants within a particular instance of the class.

Although this may seem complex right now, the basic use of class templates is easy once you see a few examples. In fact, you may be using class templates already in your programs. Many of the container classes, such as vector, in the standard C++ library are implemented as class templates.

The much celebrated CrudeStack class from the last lesson will be used in our examples. For reference, it is reproduced here with the int data type being stored. Typically, when building class templates, it is easier to first write and debug a concrete class. This class is then turned into a template. Here is the concrete "int" version of CrudeStack. I have dropped the "Crude" part of the class name, removed exception handling and slightly modified the push and pop methods in order to simplify the presentation.

class Stack {
    Stack() : index(-1) {}
    ~Stack() {}
    void push(int val)
        // Increment index, then store
        data[++index] = val;
    int pop()
        // Retrieve, then decrement index
        return data[index--];

    int data[100];
    int index;

Previous Page       Next Page