Now consider the Shape
inheritance hierarchy in Fig. 11.3. This hierarchy begins with base class Shape
. Classes TwoDimensionalShape
and ThreeDimensionalShape
derive from base class Shape
—a Shape
is a TwoDimensionalShape
or is a ThreeDimensionalShape
. The third level of this hierarchy contains more specific types of TwoDimensionalShape
s and ThreeDimensionalShape
s. As in Fig. 11.2, we can follow the arrows from the bottom of the diagram upwards to the topmost base class in this hierarchy to identify several is-a relationships. For instance, a Triangle
is a TwoDimensionalShape
and is a Shape
, while a Sphere
is a ThreeDimensionalShape
and is a Shape
.
To specify that class TwoDimensionalShape
(Fig. 11.3) is derived from (or inherits from) class Shape
, class TwoDimensionalShape
’s definition could begin as follows:
class TwoDimensionalShape : public Shape
This is an example of public inheritance, the most commonly used form. We’ll also discuss private inheritance and protected inheritance (Section 11.5). With all forms of inheritance, private
members of a base class are not accessible directly from that class’s derived classes, but these private
base-class members are still inherited (i.e., they’re still considered parts of the derived classes). With public
inheritance, all other base-class members retain their original member access when they become members of the derived class (e.g., public
members of the base class become public
members of the derived class, and, as we’ll soon see, protected
members of the base class become protected
members of the derived class). Through inherited base-class member functions, the derived class can manipulate private
members of the base class (if these inherited member functions provide such functionality in the base class). Note that friend
functions are not inherited.
Inheritance is not appropriate for every class relationship. In Chapter 9, we discussed the has-a relationship, in which classes have members that are objects of other classes. Such relationships create classes by composition of existing classes. For example, given the classes Employee
, BirthDate
and TelephoneNumber
, it’s improper to say that an Employee
is a BirthDate
or that an Employee
is a TelephoneNumber
. However, it is appropriate to say that an Employee
has a BirthDate
and that an Employee
has a TelephoneNumber
.
It’s possible to treat base-class objects and derived-class objects similarly; their commonalities are expressed in the members of the base class. Objects of all classes derived from a common base class can be treated as objects of that base class (i.e., such objects have an is-a relationship with the base class). In Chapter 12, we consider many examples that take advantage of this relationship.