Game Development Reference
In-Depth Information
Chapter 10
Building Games with Inheritance
Being a productive video game developer involves writing well-organized code that can be reused
as often as possible. C++ classes provide a feature named inheritance that helps us achieve both
of these goals. Inheritance allows us to create generalized base classes that can be derived from to
create classes with a more specific purpose. In this chapter you learn how this allows us to share
behavior among classes.
Inheriting from a Base Class
The classic example used to explain inheritance to new programmers is that of motor vehicles. There
are multiple categories of vehicles, including cars, motorbikes, and trucks. All of these things can be
thought of as vehicles and therefore can be included in a vehicle category. All have common features
such as wheels, engines, and lights but all are obviously very different. If we were to make a game
that included vehicles we could easily represent these in a class hierarchy. Figure 10-1 shows how
we can visualize our class structure.
Vehicle
Car
Motorbike
Truck
Figure 10-1. The vehicle class hierarchy
The simple diagram in Figure 10-1 shows that we will have a base class named Vehicle and that
there will be three derived classes, one named Car , one named Motorbike , and one named Truck .
Listing 10-1 shows the code for the Vehicle class.
111
 
Search WWH ::




Custom Search