Access specifiers in C++

Previous: C++

In C++, access specifiers control how class, struct, or union members can be accessed from outside the class or by derived types. The three available specifiers are public, protected, and private.

Public and private are the most commonly used, while protected is mainly relevant in inheritance hierarchies. It allows derived classes to access certain members while still hiding them from outside code.

The following table summarizes the accessibility rules:

Access LevelAccessible by Class ItselfAccessible by Derived ClassesAccessible by External Code
Publicyesyesyes
Protectedyesyesno
Privateyesnono

The next table shows how access specifiers interact with different forms of inheritance. The rows represent the access specifiers of members in the base class, and the columns represent the type of inheritance used by the derived class.

Access specifier in base classPublic InheritanceProtected InheritancePrivate Inheritance
PublicPublicProtectedPrivate
ProtectedProtectedProtectedPrivate
PrivateInaccessibleInaccessibleInaccessible

Links to this note