public
, protected
and private
InheritanceWhen deriving a class from a base class, the base class may be inherited through public
, protected or private
inheritance. We normally use public
inheritance in this book. Use of protected
inheritance is rare. Chapter 19 demonstrates private
inheritance as an alternative to composition. Figure 11.16 summarizes for each type of inheritance the accessibility of base-class members in a derived class. The first column contains the base-class member access specifiers.
When deriving a class with public
inheritance, public
members of the base class become public
members of the derived class, and protected
members of the base class become protected
members of the derived class. A base class’s private
members are never accessible directly from a derived class, but can be accessed through calls to the public
and protected
member functions of the base class.
When deriving a class with protected
inheritance, public
and protected
members of the base class become protected
members of the derived class. When deriving a class with private
inheritance, public
and protected
members of the base class become private
members (e.g., the functions become utility functions) of the derived class. private
and protected
inheritance are not is-a relationships, because the base class’s public
members are not accessible to the derived class’s client code.
Base-class member-access specifier | Type of inheritance | ||
---|---|---|---|
public inheritance |
protected inheritance |
private inheritance |
|
public |
Can be accessed directly by member functions, |
Can be accessed directly by member functions and |
Can be accessed directly by member functions and |
protected |
Can be accessed directly by member functions and |
Can be accessed directly by member functions and |
Can be accessed directly by member functions and |
private |
Hidden in derived class. Can be accessed by member functions and |
Hidden in derived class. Can be accessed by member functions and |
Hidden in derived class. Can be accessed by member functions and |