Game Development Reference
In-Depth Information
Method Overriding
Earlier in this chapter, you saw how we can change the number of wheels in derived classes by
changing the value of a variable in the derived class's constructor. Although that is a more correct
method for achieving this, I will show you how we could have achieved a similar outcome using
method overriding in this chapter. To use method overriding we will create a GetNumberOfWheels
method in each of our three classes. Listing 10-10 shows these methods.
Listing 10-10. Overriding GetNumberOfWheels
unsigned int Vehicle::GetNumberOfWheels() const
{
return 0;
}
unsigned int Car::GetNumberOfWheels() const
{
return 4;
}
unsigned int Motorcycle::GetNumberOfWheels() const
{
return 2;
}
Now each of your classes has a method with an identical name. In the PrintNumberOfWheels method
so far, each call to GetNumberOfWheels called Vehicle::GetNumberOfWheels , which returned the value
stored in m_numberOfWheels . With method overriding the compiler will call the GetNumberOfWheels
method for the appropriate class; therefore, we will see calls to Car::GetNumberOfWheels and
Motorcycle::GetNumberOfWheels in the proper place in our PrintNumberOfWheels function.
Updating Text Adventure
The Text Adventure game you are building has fairly limited functionality at this point. In this chapter
we are going to add some rooms to the game and update Player to be inherited from a class named
Entity .
Creating an Entity Class
Entity will be our game's base class for all objects that exist in the game world. Listing 10-11 shows
the code for Entity .
Listing 10-11. The Entity Class
class Entity
{
public:
void Update() {}
};
 
Search WWH ::




Custom Search