DevAcademia lesson/C++ Classes
Access Specifiers in Inheritance
Topic progressTopic 96 of 109 - 88% complete
~8 min lesson29 learning blocks4 code examples1 checks/interactions
Lesson outline
Core Concepts
Access specifiers in inheritance affect two main aspects:
- Derived Class Access: How inherited members can be used within the derived class.
- Client Code Access: How inherited members can be accessed through derived objects.
The three specifiers (public, protected, private) define different levels of encapsulation.
Detailed Access Rules
| Base Member | Inheritance Type | In Derived Class | Through Derived Object |
|---|---|---|---|
| public | public | public | public |
| public | protected | protected | inaccessible |
| public | private | private | inaccessible |
| protected | public | protected | inaccessible |
| protected | protected | protected | inaccessible |
| protected | private | private | inaccessible |
| private | any | inaccessible | inaccessible |
Defaults & Conversions
- Default inheritance access: If you omit the specifier,
class Derived : Basedefaults to private inheritance;struct Derived : Basedefaults to public inheritance. - Implicit upcasting: With public inheritance, clients can implicitly convert
Derived*/Derived&toBase*/Base&. With protected or private inheritance, such conversions are not accessible to client code (they are only permitted within the derived class and, for protected, its further derived classes/friends).
Practical Scenarios
Public Inheritance:
- Models 'is-a' relationships.
- Preserves the base class interface.
- Used in most inheritance cases.
Protected Inheritance:
- Rarely used in practice.
- Converts public base members to protected.
- Useful when derived classes need access but external clients should not.
Private Inheritance:
- Models 'implemented-in-terms-of' relationships.
- Completely hides the base class interface from clients.
- Often replaced by composition when possible.
Advanced Techniques
Using-declarations to re-expose: Bring hidden or redefined base names into the desired access section to change their accessibility in the derived interface.
Using Declarations: Bring hidden or redefined names into scope.
Friendship and Inheritance: Friend relationships are not inherited automatically.
Design Guidelines
- Prefer public inheritance when modeling interface relationships.
- Use private inheritance only for implementation reuse.
- Avoid protected inheritance; consider private inheritance or composition instead.
- Document non-public inheritance relationships clearly.
- Use
usingdeclarations selectively to re-expose only the members you intend to. - Do not alter access levels to bypass good design practices.
Was this topic clear?