Inheritance
A class can inherit from zero or more base classes. A class with at least one base class is said to be a derived class. A derived class inherits all the data members and member functions of all of its base classes and all of their base classes, and so on. A class’s immediate base classes are called direct base classes . Their base classes are indirect base classes. The complete set of direct and indirect base classes is sometimes called the ancestor classes .
A class can derive directly from any number of base classes. The
base-class names follow a colon and are separated by commas. Each class
name can be prefaced by an access specifier (described later in this
chapter). The same class cannot be listed more than once as a direct
base class, but it can appear more than once in the inheritance graph.
For example, derived3
in the
following code has base2
twice in its
inheritance tree, once as a direct base class, and once as an indirect
base class (through derived2
):
class base1 { ... }; class derived1 : public base1 { ... }; class base2 { ... } class derived2 : public derived1, public base2 { ... } class derived3 : protected derived2, private base2 { ... }
A derived class can access the members that it inherits from an ancestor class, provided the members are not private. (See Section 6.5 later in this chapter for details.) To look up a name in class scope, the compiler looks first in the class itself, then in direct base classes, then in their direct base classes, and ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.