Game Development Reference
In-Depth Information
Listing 10-5. The Motorcycle Class
class Motorcycle : public Vehicle
{
public:
Motorcycle();
};
Motorcycle::Motorcycle()
{
m_numberOfWheels = 2;
}
You can see that we add our new class to PrintNumberOfWheels in Listing 10-6.
Listing 10-6. Adding Motorcycle to PrintNumberOfWheels
void PrintNumberOfWheels()
{
Vehicle vehicle;
Car car;
Motorcycle motorcycle;
std::cout << vehicle.GetNumberOfWheels() << std::endl;
std::cout << car.GetNumberOfWheels() << std::endl;
std::cout << motorcycle.GetNumberOfWheels() << std::endl;
}
Motorcycle inherits from Vehicle , just as Car does, but it sets the number of wheels to 2 and this is
printed out when we call the PrintNumberOfWheels function.
You now understand the basics of how to create classes that inherit behaviors from base classes.
Now I'll move on to show you how this works in practice.
Constructors and Destructors in Derived Classes
In the previous section you saw that we can set values in member variables belonging to our parent
class if the variables were declared as protected or public . Listing 10-7 shows the constructors
from the Vehicle , Car , and Motorbike classes.
Listing 10-7. Your Vehicle , Car , and Motorbike Constructors
Vehicle::Vehicle()
: m_numberOfWheels(0)
{
}
Car::Car()
{
m_numberOfWheels = 4;
}
 
Search WWH ::




Custom Search