When you declare a derived class, an access specifier
can precede each base class in the base list of the derived class.
This does not alter the access attributes of the individual members
of a base class as seen by the base class, but allows the derived
class to restrict the access control of the members of a base class.
You can derive classes using any of the three access specifiers:
- In a public base class, public and protected
members of the base class remain public and protected members of the
derived class.
- In a protected base class, public and protected
members of the base class are protected members of the derived class.
- In a private base class, public and protected
members of the base class become private members of the derived class.
In all cases, private members of the base class remain
private. Private members of the base class cannot be used by the derived
class unless friend declarations within the base class explicitly
grant access to them.
In the following example, class
d is
derived publicly from class
b. Class
b is
declared a public base class by this declaration.
class b { };
class d : public b // public derivation
{ };
You can use both a structure and a class as base classes
in the base list of a derived class declaration:
- If the derived class is declared with the keyword class,
the default access specifier in its base list specifiers is private.
- If the derived class is declared with the keyword struct,
the default access specifier in its base list specifiers is public.
In the following example, private derivation is used by
default because no access specifier is used in the base list and the
derived class is declared with the keyword
class:
struct B
{ };
class D : B // private derivation
{ };
Members and friends of a class can implicitly convert
a pointer to an object of that class to a pointer to either:
- A direct private base class
- A protected base class (either direct or indirect)