O'Reilly logo

SDL Game Development by Shaun Mitchell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing polymorphism

This leads us to our next OOP feature, polymorphism. What polymorphism allows us to do is to refer to an object through a pointer to its parent or base class. This may not seem powerful at first, but what this will allow us to do is essentially have our Game class need only to store a list of pointers to one type and any derived types can also be added to this list.

Let us take our GameObject and Player classes as examples, with an added derived class, Enemy. In our Game class we have an array of GameObject*:

std::vector<GameObject*> m_gameObjects;

We then declare four new objects, all of which are GameObject*:

GameObject* m_player;
GameObject* m_enemy1;
GameObject* m_enemy2;
GameObject* m_enemy3;

In our Game::init function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required