Game Development Reference
In-Depth Information
Something similar is happening in the
Update
method of the
Ball
class. At the end
of that method, we call the
Update
method of the
ThreeColorGameObject
class, so that
the position is changed according to the velocity. You can also see an example of
this in the new
PaintCan
class, which is also a subclass of
ThreeColorGameObject
.
10.5.4 Polymorphism
Because of the inheritance mechanism, there are now some interesting things hap-
pening. Since a cannon object is a three colored game object, this instruction is
allowed:
ThreeColorGameObject cannon =
new
Cannon(...);
Now suppose that we would then execute the following instruction:
cannon.Reset();
Which version of the
Reset
method would be called? The one in the
Cannon
class
or the one in the
ThreeColorGameObject
class? Although the variable
cannon
is of
type
ThreeColorGameObject
, it actually refers to an object of type
Cannon
. When you
run the program, the compiler maintains a so-called
vtable
which contains for each
object in the program to which inheritance tree it belongs and what that tree looks
like. Whenever a virtual method is called, like what happens here in the case of
the
Reset
method, the compiler looks in the table to find out which version of the
method should be called. In this case, it will see that we're dealing with a
Cannon
object, so it will call the version of the
Reset
method that is defined in the
Cannon
class.
This effect is called
polymorphism
and it comes in very handy sometimes. An-
other example where polymorphism is responsible for the behavior of the program
is when we call the
Run
method on the
game
variable. The
Run
method is defined
inside the
Game
class. This method does not know that it happens to work with a
Painter
object. Because of polymorphism, when, for instance, the
Update
method is
called from within the
Run
method, automatically the right version of the method is
called, which would be the
Update
method that we defined in the
Painter
class.
Another example of where polymorphism is useful is when a game company
wants to release an extension of their game. For example, they might want to intro-
duce a few new enemies, or skills that a player can learn. They can provide these
extensions as subclasses of generic
Enemy
and
Skill
classes. The actual game engine
would then use these objects without having to know which particular skill or en-
emy it is dealing with. It simply calls the methods that were defined in the generic
classes.