Whether the derived-to-base conversion (§ 15.2.2, p. 597) is accessible depends on which code is trying to use the conversion and may depend on the access specifier used in the derived class’ derivation. Assuming D
inherits from B
:
• User code may use the derived-to-base conversion only if D
inherits publicly from B
. User code may not use the conversion if D
inherits from B
using either protected
or private
.
• Member functions and friends of D
can use the conversion to B
regardless of how D
inherits from B
. The derived-to-base conversion to a direct base class is always accessible to members and friends of a derived class.
• Member functions and friends of classes derived from D
may use the derived-to-base conversion if D
inherits from B
using either public
or protected
. Such code may not use the conversion if D
inherits privately from B
.
For any given point in your code, if a public
member of the base class would be accessible, then the derived-to-base conversion is also accessible, and not otherwise.
Key Concept: Class Design and protected
Members
In the absence of inheritance, we can think of a class as having two different kinds of users: ordinary users and implementors. Ordinary users write code that uses objects of the class type; such code can access only the public
(interface) members of the class. Implementors write the code contained in the members and friends of the class. The members and friends of the class can access both the public
and private
(implementation) sections.
Under inheritance, there is a third kind of user, namely, derived classes. A base class makes protected
those parts of its implementation that it is willing to let its derived classes use. The protected
members remain inaccessible to ordinary user code; private
members remain inaccessible to derived classes and their friends.
Like any other class, a class that is used as a base class makes its interface members public
. A class that is used as a base class may divide its implementation into those members that are accessible to derived classes and those that remain accessible only to the base class and its friends. An implementation member should be protected
if it provides an operation or data that a derived class will need to use in its own implementation. Otherwise, implementation members should be private
.