Compartir a través de


Access Specifiers for Base Classes

Two factors control which members of a base class are accessible in a derived class; these same factors control access to the inherited members in the derived class:

  • Whether the derived class declares the base class using the public access specifier in the class-head (class-head is described in the Grammar section in Defining Class Types).

  • What the access to the member is in the base class.

The following table shows the interaction between these factors and how to determine base-class member access.

Member Access in Base Class

private

protected

Public

Always inaccessible regardless of derivation access

Private in derived class if you use private derivation

Private in derived class if you use private derivation

 

Protected in derived class if you use protected derivation

Protected in derived class if you use protected derivation

 

Protected in derived class if you use public derivation

Public in derived class if you use public derivation

The following example illustrates this:

// access_specifiers_for_base_classes.cpp
class BaseClass
{
public:
    int PublicFunc();    // Declare a public member.
protected:
    int ProtectedFunc(); // Declare a protected member.
private:
    int PrivateFunc();   // Declare a private member.
};

// Declare two classes derived from BaseClass.
class DerivedClass1 : public BaseClass
{
};

class DerivedClass2 : private BaseClass
{
};

int main()
{
}

In DerivedClass1, the member function PublicFunc is a public member and ProtectedFunc is a protected member because BaseClass is a public base class. PrivateFunc is private to BaseClass, and it is inaccessible to any derived classes.

In DerivedClass2, the functions PublicFunc and ProtectedFunc are considered private members because BaseClass is a private base class. Again, PrivateFunc is private to BaseClass, and it is inaccessible to any derived classes.

You can declare a derived class without a base-class access specifier. In such a case, the derivation is considered private if the derived class declaration uses the class keyword. The derivation is considered public if the derived class declaration uses the struct keyword. For example, the following code:

class Derived : Base
...

is equivalent to:

class Derived : private Base
...

Similarly, the following code:

struct Derived : Base
...

is equivalent to:

struct Derived : public Base
...

Note that members declared as having private access are not accessible to functions or derived classes unless those functions or classes are declared using the friend declaration in the base class.

A union type cannot have a base class.

Nota

When specifying a private base class, it is advisable to explicitly use the private keyword so users of the derived class understand the member access.

See Also

Reference

Member-Access Control