Reader small image

You're reading from  SDL Game Development

Product typeBook
Published inJun 2013
Reading LevelBeginner
PublisherPackt
ISBN-139781849696821
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Shaun Mitchell
Shaun Mitchell
author image
Shaun Mitchell

Shaun Mitchell is a developer at a high profile online gaming company. He holds a BSc in Game Programming and Development from Qantm College / SAE Institute London. Shaun is also a moderator and active member of the <dream.in.code> programming community.
Read more about Shaun Mitchell

Right arrow

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 we can then create instances of the objects using their individual types:

m_player = new Player();
m_enemy1 = new Enemy();
m_enemy2 = new Enemy();
m_enemy3 = new Enemy();

Now they can be pushed into the array of GameObject*:

m_gameObjects.push_back...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
SDL Game Development
Published in: Jun 2013Publisher: PacktISBN-13: 9781849696821

Author (1)

author image
Shaun Mitchell

Shaun Mitchell is a developer at a high profile online gaming company. He holds a BSc in Game Programming and Development from Qantm College / SAE Institute London. Shaun is also a moderator and active member of the <dream.in.code> programming community.
Read more about Shaun Mitchell