Class Templates in C++


Class Template:

As you might have seen the advantage of function template is that, the code gets compact, also by writing less number of lines of code(LoC), we can achieve our desired feature from a function template.

On the other hand, a class template has a feature to let programmer create a single class that can work for family of classes. Its major use and implementation can be while handling Matrices. By writing a class in a generic way, we can save lot of memory spaces (consider matrix multiplication, for say).

The general syntax to declare a class template is :

Here, ‘T’, is the parametrized data-type. We should note that, all the methods within the class template are implicitly declared as template. If the method definition is within the class itself, there is no change (normal method definition within the class).

In case , method is defined outside of the class, for template class it must follow the given general syntax:

[Note: Class Template and Template Class can be interchangeably used, both these terms mean the same i.e generic class]

In order to create the object of the generic class, the general syntax is:

Now, it must have made sense to you, how is the type determined for the class-when it was declared as a generic type. For example: for template class Sample, the Object could have been declared as :

A simple program to demonstrate the concept:

Another noticeable concept is that, if the method returns an Object of generic type, the parametrized data-type must be passed there as well. Note, the return-type, MyMatrix<T>.

Would You Mind Sharing?


Be the first to comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.