From the course: Complete Guide to C++ Programming Foundations

Unlock this course with a free trial

Join today to access over 24,400 courses taught by industry experts.

Template classes

Template classes

- [Instructor] Templates allow us to create flexible and reusable code for various data types. And they are not limited to functions, we can also use them to create classes. Let's start with an example in the context of an adventure game. Here we are defining a game entity template class in line nine. This class has two private data members, x and y, to represent positions in a two-dimensional space. Notice that the type T is a placeholder for any data type, and it will be determined when we instantiate an object of this class. The class constructor in line 12, initializes x and y. And the print position function in line 13 outputs the entity's position. Now, in the main function, we instantiate an object of the game entity class in line 19. This is a template class instantiation for integers. Here we are creating a game entity object called enemy, which keeps its coordinates as integer, starting at location 10, 20. Then in lines 20 and 21, I am printing the enemy's position. Let's…

Contents