Game Development Reference
In-Depth Information
You create virtual methods by adding the
virtual
keyword to the beginning of the method signature.
The method
GetNumberOfWheels
is now a
virtual
method. To get the benefit of this, Listing 11-2
updates the
Car
and
Motorcycle
classes to make their
GetNumberOfWheels
methods
virtual
.
Listing 11-2. Making
GetNumberOfWheels Virtual
in
Car
and
Motorcycle
class Car : public Vehicle
{
public:
Car();
~Car();
virtual unsigned int GetNumberOfWheels() const
{
return 4;
}
};
class Motorcycle : public Vehicle
{
public:
Motorcycle();
~Motorcycle();
virtual unsigned int GetNumberOfWheels() const
{
return 2;
}
};
The code in Listing 11-2 completes our updates to the
GetNumberOfWheels
methods in the
Vehicle
,
Car
, and
Motorcycle
classes. Listing 11-3 modifies the
PrintNumberOfWheels
method to make use of
polymorphism.
Listing 11-3. Using Polymorphism in
PrintNumberOfWheels
void PrintNumberOfWheels()
{
Vehicle vehicle;
Car car;
Motorcycle motorcycle;
Vehicle* pVehicle = &vehicle;
std::cout << pVehicle->GetNumberOfWheels() << std::endl;
pVehicle = &car;
std::cout << pVehicle->GetNumberOfWheels() << std::endl;
pVehicle = &motorcycle;
std::cout << pVehicle->GetNumberOfWheels() << std::endl;
}