Lesson 07: Inheritance

The idea of classes leads to the idea of inheritance. In our daily lives, we use the concept of classes being divided into subclasses. You know that the class of animals is divided into mammals, fishes, insects, birds, and so on. The class of vehicles is divided into cars, trucks, buses, and motorcycles.

The principle in this sort of division is that each subclass shares common characteristics with the class from which it's derived. Cars, trucks, buses, and motorcycles all have wheels and a motor and are used to transport people or goods; these are the defining characteristics of vehicles. In addition to the characteristics shared with other members of the class, each subclass also has its own particular characteristics: Buses, for instance, have seats for many people, whereas trucks have space for hauling heavy loads. The inheritance relationship is shown in Figure 1.

inheritance Vehicles
Figure 1: The Object Relationship of Vehicles

In a similar way, an OOP class can be used as the basis for one or more different subclasses. In C++, the original class is called the base class; other classes can be defined that share its characteristics, but add their own as well. These are called derived classes. The derived class inherits all the capabilities of the base class but can add embellishments and refinements of its own. The base class is unchanged by this process. The inheritance relationship is shown in Figure 2.

01 inheritance
Figure 2: Inheritance

Inheritance Syntax

The simplest example of inheritance requires two classes: a base class and a derived class. The base class does not need any special syntax. The derived class, on the other hand, must indicate that it's derived from the base class. This is done by placing a colon (:) after the name of the derived class, followed by a keyword such as public and then the base class name.

The general syntax of a derived class is:

class className : accessSpecifier baseClassName
{
member_List;
};

Where accessSpecifier is public, protected, or private. When no accessSpecifier is specified, it is assumed to be a private inheritance. The colon (like the arrow in inheritance diagrams) means "is derived from."

© 2024 Air Supply Information Center (Air Supply BBS)