Inheritance levels in OOP and the importance of planning ahead.

23 Jun, 2015 @ 16:02:24 by

For those that are new to object oriented programming or are unfamiliar with inheritance’s more complex concepts, i will share some tips from my game making experience.
When you make a game, you tend to forget about staying generic and allow for more possibilities. Because you have an immediate need, you want that object to behave that way and that could never change, surely. Except, it probably will!
For instance, say you are making a shoot’em’up game, like I am. You have your game logic set and you call an update method for each gameobject in your game loop. Your basic type for gameplay objects is gameobject.
Your enemies will fire bullets, so you made that update method return a bullet type object.
Pseudo code:
for all gameobjects
new bullet = return value of current gameobject update method
if bullet isn't null
add bullet to bulletList

However, what if you wanted to fire SEVERAL bullets ? Oh that’s simple, you just have to return an array / vector of bullets, then.
Yes, but what if you wanted to fire something else ?
If you instead use the basic “gameobject” type, that means you can return any type of gameobject instead of “just” a bullet.
Returning an array of gameobjects allows you to be free to do whatever you want.
Want to have an enemy shooting enemies ? You can (think of a launchbase for instance).
Want to use the update method to “shoot” coins when the enemy is dead ? You can.
Want to make an enemy that can replicate itself ? You can.

Well, it’s all cool and dandy, you think…but what about object specific method calls ? What if i need the returned object to be of a specific type ?
Thankfully, you can always typecast it and have access to all the objects functions.

Hope this helps some of you young programmers out there! Have fun coding…