Contributors: 7 Sunday, July 31, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

Basic Class Template

Download c++ eBook


The basic idea of a class template is that the template parameter gets substituted by a type at compile time. The result is that the same class can be reused for multiple types. The user specifies which type will be used when a variable of the class is declared. Three examples of this are shown in main():

#include <iostream>
using std::cout;

template <typename T>         // A simple class to hold one number of any type
class Number {
    void setNum(T n);         // Sets the class field to the given number
    T plus1() const;          // returns class field's "follower"
    T num;                    // Class field

template <typename T>         // Set the class field to the given number
void Number<T>::setNum(T n) {
    num = n;

template <typename T>         // returns class field's "follower"
T Number<T>::plus1() const {
    return num + 1;

int main() {
    Number<int> anInt;        // Test with an integer (int replaces T in the class)
    cout << "My integer + 1 is " << anInt.plus1() << "\n";     // Prints 2

    Number<double> aDouble;   // Test with a double
    cout << "My double + 1 is " << aDouble.plus1() << "\n";    // Prints 4.14159

    Number<float> aFloat;     // Test with a float
    cout << "My float + 1 is " << aFloat.plus1() << "\n";      // Prints 2.4

    return 0;  // Successful completion