Saturday, November 19, 2016

Template Class in C++: Simple Queue Class Example

In this tutorial, I would like to demonstrate C++ template class by providng a very simple Queue class example.

The following shows its source file queue.cpp and header file queue.hpp:

There are a couple of important things to note.

First, the header file actually #includes the source file. This is because Queue class is a template class. In C++, a template class declaration and definition cannot be separated, and therefore by #includeing the source file, the two files are effectively treated as a single file. Of course, you may choose to simply define all the methods in the header file and get rid of the queue.cpp file.

Second, copy constructor, copy operator, and destructors are defined explicitly, because it assigns dynamic memory allocation. Please refer to this post for more details on the Rule of Three.

Lastly, when you compile sources that make use of this template class, all you need to do is to #include the header file. For instance, the compile command should look like:
$ g++ main.cpp

Notice there is no need to compile queue.cpp file or queue.hpp file separately. All you need to do is to make sure that queue.hpp file #includequeue.cpp file, and main.cpp #includes queue.hpp file.

No comments:

Post a Comment