I can relate to what dandy was saying. One of the problems when you're waist-deep in programming books is that you learn all the concepts (the "what", if you will) but you don't really learn the "why" aside from contrived examples. I knew all about inheritance and polymorphism
years before I ever really understand
why it was useful. It's useless without context.
Here's a really simple, common example from a game development perspective. Let's say that at every frame, you iterate over all your objects in the game and update them (which is very common). Here's some code in pseudo-C# for an example:
Code: Select all
Game.Update()
{
for (int i = 0; i < gameObjects.Count; i++)
{
gameObjects[i].Update();
}
}
Let's say each game object is of a base type GameObject. Well, clearly you'll want to update a "building" in a different way than a "player" or an "enemy". In the player's Update function, you might check for user input. In the enemy's update, you might check to see if they're close to a Player, in which case they should attack. It's a simple example, but it's relevant. This is much easier than having separate classes for each type of object in the game, which don't relate to each other in any way. The alternative would be something like:
Code: Select all
for (int i = 0; i < players.Count; i++)
{
players[i].Update();
}
for (int i = 0; i < enemies.Count; i++)
{
enemies[i].Update();
}
for (int i = 0; i < buildings.Count; i++)
{
buildings[i].Update();
}
But I should mention, the more you work with inheritance, the more value you'll see in using interfaces (in the case of C#) instead of inheritance whenever possible. Instead of deep inheritance hierarchies (e.g. GameObject<-MoveableObject<-Enemy<-Spider), you'll want objects that have "attached" behaviors via interfaces (or abstract base classes in C++ I would presume). Otherwise you get into situations in which you have trouble classifying objects because they could fit into two distinct branches of the inheritance tree. So instead you could have:
class Spider : IMoveable, ICollidable
{
...
}
class Player : IInputReceiver, IMoveable, ICollidable
{
...
}
class Building : ICollidable
{
...
}
This is a pretty "flat" hierarchy; the alternative would require a lot of repeated code and much more headache. Anyway, that's it for now. :P