This chapter continues our discussion of object-oriented programming (OOP) by introducing inheritance in which you create a class that absorbs an existing class’s capabilities, then customizes or enhances them. Inheritance can save time during program development by taking advantage of proven, high-quality software.
When creating a class, instead of writing completely new data members and member functions, you can specify that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is called the derived class. Other programming languages, such as Java and C#, refer to the base class as the super-class and the derived class as the subclass. A derived class represents a more specialized group of objects.
C++ offers public
, protected
and private
inheritance. In this chapter, we concentrate on public
inheritance and briefly explain the other two. With public
inheritance, every object of a derived class is also an object of that derived class’s base class. However, baseclass objects are not objects of their derived classes. For example, if we have Vehicle
as a base class and Car
as a derived class, then all Car
s are Vehicle
s, but not all Vehicle
s are Car
s—for example, a Vehicle
could also be a Truck
or a Boat
.
We distinguish between the is-a relationship and the has-a relationship. The is-a relationship represents inheritance. In an is-a relationship, an object of a derived class also can be treated as an object of its base class—for example, a Car
is a Vehicle
, so any attributes and behaviors of a Vehicle
are also attributes and behaviors of a Car
. By contrast, the hasa relationship represents composition, which was discussed in Chapter 9. In a has-a relationship, an object contains one or more objects of other classes as members. For example, a Car
has many components—it has a steering wheel, has a brake pedal, has a transmission, etc.