Game Development Reference
In-Depth Information
The Car class is inheriting from Vehicle using public inheritance. You can inherit one class from
another by following the class name with a colon, followed by public then the name of the class you
wish to derive from. Listing 10-2 shows that we have derived Car from Vehicle .
If you enter the code from Listing 10-2 into your integrated development environment (IDE) and try to
compile you will be given a compiler error. The compiler cannot access m_numberOfWheels in the Car
constructor as it is a private member of Vehicle . One option would be to make m_numberOfWheels a
public variable; however, this would break our encapsulation and allow the variable to be accessed
from anywhere in our code. A better option is to use the protected keyword. Listing 10-3 updates
the Vehicle class with the protected keyword.
Listing 10-3. Using protected in Vehicle
class Vehicle
{
protected:
unsigned int m_numberOfWheels;
public:
Vehicle();
unsigned int GetNumberOfWheels() const;
};
The protected keyword makes variables behave as though they are private to outside code; that is,
they still cannot be accessed directly by calling code. The key difference to private member variables
is that they can be accessed by derived classes. By declaring m_numberOfWheels as protected in the
Car class we can now access it directly in Car and set the number of wheels to 4. Listing 10-4 shows
some code to print the number of wheels each vehicle type contains.
Listing 10-4. Printing the Number of Wheels
void PrintNumberOfWheels()
{
Vehicle vehicle;
Car car;
std::cout << vehicle.GetNumberOfWheels() << std::endl;
std::cout << car.GetNumberOfWheels() << std::endl;
}
This function will result in 0 being printed followed by the number 4. It's important that you
note what this function has achieved. The Car class defined in Listing 10-2 does not contain a
GetNumberOfWheels method, nor does it have a variable to store a number of wheels. The Car class
has inherited these from the Vehicle class. Listing 10-5 shows how you can inherit another class
from Vehicle , this time Motorcycle .
 
Search WWH ::




Custom Search