11.5 public, protected and private Inheritance

When 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.

Fig. 11.16 Summary of base-class member accessibility in a derived class.

Base-class member-access specifier Type of inheritance
public inheritance protected inheritance private inheritance
public

public in derived class.

Can be accessed directly by member functions, friend functions and nonmember functions.

protected in derived class.

Can be accessed directly by member functions and friend functions.

private in derived class.

Can be accessed directly by member functions and friend functions.

protected

protected in derived class.

Can be accessed directly by member functions and friend functions.

protected in derived class.

Can be accessed directly by member functions and friend functions.

private in derived class.

Can be accessed directly by member functions and friend functions.

private

Hidden in derived class.

Can be accessed by member functions and friend functions through public or protected member functions of the base class.

Hidden in derived class.

Can be accessed by member functions and friend functions through public or protected member functions of the base class.

Hidden in derived class.

Can be accessed by member functions and friend functions through public or protected member functions of the base class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset