Game Development Reference
In-Depth Information
Motorcycle::Motorcycle()
{
m_numberOfWheels = 2;
}
The Vehicle class constructor sets m_numberOfVehicles to 0 in an initializer list. Car and Motorbike
assign the values directly as an initializer list cannot be used on nonmember variables from our base
class. What you might be surprised to hear is that the Vehicle constructor is called automatically
when we create a Car or Motorbike object. You can see this in practice by adding some logging code
to the constructors, which we do in Listing 10-8.
Listing 10-8. Adding Logging to Your Constructors
Vehicle::Vehicle()
: m_numberOfWheels(0)
{
std::cout << "Vehicle Constructed" << std::endl;
}
Car::Car()
{
m_numberOfWheels = 4;
std::cout << "Car Constructed" << std::endl;
}
Motorcycle::Motorcycle()
{
m_numberOfWheels = 2;
std::cout << "Motorcycle Constructed" << std::endl;
}
If you execute the PrintNumberOfVehicles function from Listing 10-6 once more you will see that we
have some new text in the output. It should read:
Vehicle Constructed
Vehicle Constructed
Car Constructed
Vehicle Constructed
Motorcycle Constructed
0
4
2
Vehicle Constructed is printed three different times. That is because the Vehicle constructor
is being called each time any class that derives from Vehicle is instantiated. The order of the
constructors is important: The constructors of parent classes are called before the constructors of
derived classes. You can see this in action where the Vehicle Constructed output text is printed
before both Car Constructed and Motorcycle Constructed .
 
Search WWH ::




Custom Search