Game Development Reference
In-Depth Information
Chapter 11
Designing Game Code
with Polymorphism
You saw how inheritance can be used to design reusable code in the last chapter. In this chapter
you will learn how the power of inheritance can be unlocked in much more useful ways through
the power of polymorphism. C++ supports the ability to access classes of different types through
pointers to a base class, known as polymorphism. The program can determine the type of the object
at runtime and call the correct method. The mechanism supplied by C++ to tell the compiler that a
method can be different in the base class to any derived classes is the virtual method.
Virtual Methods
You have seen that methods in class hierarchies can be overridden, which allows the compiler to call
a given method for a class type rather than call the version from the base class when accessing an
object of a given type. When you use polymorphism, the compiler cannot tell what the actual type of
the object is and therefore we must write our methods in a different manner. Listing 11-1 shows how
the Vehicle class can be modified to turn the GetNumberOfWheels method into a virtual method.
Listing 11-1. Creating a Virtual Method
class Vehicle
{
public:
Vehicle();
~Vehicle();
virtual unsigned int GetNumberOfWheels() const
{
return 0;
}
};
127
 
Search WWH ::




Custom Search