Friday, Jan 19th

Last update12:59:40 PM GMT

C++ Class Templates

Write e-mail

After knowing about the function templates, the next step is Class Templates. The most prominent use of Class templates has been in STL (Standard Template Library) classes of C++ like vector, list etc. The use of class templates is quite similar to function templates.

argaiv1077

For example:

template <class T>
class myClass
{
T data[2];
public:
myClass(T first, T second)
{
data[0] = first;
data[1] = second;
}
T getMax ()
{
T result;
result = (data[0] > data[1]) ? data[0]: data[1];
return result;
}
}

In the above example, the member function getMax() has been defined inline within the class. If we wish to define it outside the class declaration, we will have to precede the definition with the template <...> prefix.

template <class T>
T myClass <T>::getMax()
{
T result;
result = (data[0] > data[1]) ? data[0]: data[1];
return result;
}

How to put class templates to use is straight forward.

myClass <int> myFirstObject (2,3);
myClass <double> mySecondObject (2.0, 3.0);
int x = myFirstObject.getMax();


Share this post



Add comment

Please refrain from using slang or abusive language in the comments.
To avoid waiting for your comment to be published after being reviewed, please log in as a registered user.


Security code
Refresh

Web Hosting