The Mighty C++ Template - A simple class template
(Page 5 of 9 )
Templates can also be used to create classes. Class templates stem from the same principles as normal templates, and are used in exactly the same way. A class template allows a developer to create classes whose constructor, destructor and functions can accept different types of values, just like a function template.
To create a class template, create a new C++ project and add two files: classtemplate.h and classtemplate.cpp. Into classtemplate.h, enter the following code:
template<typename T> class MyClass
{
public:
MyClass(T x = 0, T y = 0, T z = 0) : n1(x), n2(y), n3(z) {}
T GetAverage();
private:
T n1;
T n2;
T n3;
};This code might look a little confusing at first, but allow me to explain it. Notice how we have defined the entire class in the header file this time, and not just the declaration like we did for the function template?
Firstly, we have the class declaration:
template<typename T> class MyClassA class template declaration is a bit different to a function template declaration. Firstly, between the angled brackets, we are creating a type identifier. We have used “typename” instead of “class” here, but they are interchangeable.
Next, we have the “class” keyword followed by the name of the class, “MyClass”. The class can be called anything you like, but we will use “MyClass” in this example.
{
public:
MyClass(T x = 0, T y = 0, T z = 0) : n1(x), n2(y), n3(z) {}
T GetAverage();
private:
T n1;
T n2;
T n3;
};Following the template class’s declaration, we have its default constructor and one function named GetAverage() which takes no parameters and returns a value of type T.
Notice that our constructor is accepting three variables of type T, all with a default value of zero. The constructor assigns these values to our private member variables (of type T) n1, n2 and n3 respectively. These private variables are simply used to hold the values of the variables passed in and can’t be accessed.
Next: A simple class template (contd.) >>
More C++ Articles
More By Mitchell Harper