Game Development Reference
In-Depth Information
Pure virtual methods are created by adding = 0 to the end of the method declaration. The method
then does not contain a body, as we do not wish to have any code associated with the method in
this class. Adding a pure virtual method to a class turns the class into an abstract class. Abstract
classes cannot be instantiated, which means we can no longer create Vehicle objects. You will
need to remove the instance of Vehicle in PrintNumberOfWheels . Listing 11-7 shows a version of the
function with this removed.
Listing 11-7. Removing Vehicle from PrintNumberOfWheels
void PrintNumberOfWheels()
{
Car car;
Motorcycle motorcycle;
Vehicle* pVehicle = dynamic_cast<Vehicle*>(&car);
Car* pCar = dynamic_cast<Car*>(pVehicle);
if (pCar != nullptr)
{
std::cout << pCar->GetNumberOfWheels() << std::endl;
}
pVehicle = dynamic_cast<Vehicle*>(&motorcycle);
pCar = dynamic_cast<Car*>(pVehicle);
if (pCar != nullptr)
{
std::cout << pCar->GetNumberOfWheels() << std::endl;
}
}
Another effect of the pure virtual method is that it turns Vehicle into an interface class. Interface
classes are usually simply referred to as interfaces. Any pure virtual methods in a parent class must
be overridden in a class that you wish to be able to instantiate. You might recall that the notion of
contracts was touched on in Chapter 8 when we discussed OOP. Using interfaces is one method
that you can use to define these contracts. You can try commenting out the GetNumberOfWheels
methods from the Car and Motorcycle classes to see the compiler errors that are generated.
Using Polymorphism in Text Adventure
The options that have been supplied to the player in Text Adventure have so far been coded procedurally.
You can make it much easier to add new options by using a more object-oriented approach to the
system. Listing 11-8 shows the Option interface that you can use to create future options.
Listing 11-8. The Option Class
class Option
{
protected:
PlayerOptions m_chosenOption;
std::string m_outputText;
std::string m_optionText;
 
Search WWH ::




Custom Search