← Go back

Using a (kind of) generic type variable (C++)

If you have used languages like C# you are probably familiar with interfaces.
When using an interface, you create derived classes using the interface. Afterwards you can use this interface as a variable
To store every object whose class inherits the interface.

Quick example:

Lets say you have an interface called "Car" and a class called "Ferrari" that uses the interface Car.
You could now have a variable Car myCar = new Ferrari();
And it would just work. The variable myCar would have everything that an object of type Ferrari would have.

C++ and slicing

Doing the same in C++ will not work. What you would get is called slicing. The variable myCar would only
have everything an object of type Car would have, all the information of the type Ferrari would be sliced away, thus the name slicing.

Now getting around slicing

Let's say your base class is IGameObject, you have a derived class Enemy and another derived class Player.
Now you want a variable currentObject where you can store an object of Enemy or an object of Player and still have access to all their variables and methods.

So a quick way is to use a pointer.

Here is how to do it:

First you need to create a variable as a DWORD

DWORD *currentObject;
Now create an instance of the derived class. Enemy enemy = *new Enemy();
after that you can save a pointer to enemy in the variable currentObject; currentObject = (DWORD*)(&enemy);
To read currentObject as an object of type Enemy you just have to get the pointer and cast it to the Enemy class like so Enemy *enemyInstance = (Enemy*)(currentObject);
You now have full access to all variables and methods of the enemy object.

The Concept

So here is the basic concept of what's happening above.
Instead of saving the pointer to our class instance of Enemy directly to an Enemy pointer, we now save the pointer itself as a DWORD. The DWORD will store the address to the object.

This allows us to store every possible object. At the end we will just read the pointer and cast its data to an Enemy object. Doing that you can have full access to everything stored in the variable.

But keep in mind, that you have to know the type that you are storing. At this point the compiler does not know what you are storing.
After all this will save you a bunch of time and a possible headache when dealing with template (T) -types.