C++ private inheritance: under private inheritance, how are the base class’s public members treated in the derived class interface?
-
APublic members of the base class become protected members of derived class.
-
BPublic members of the base class become private members of derived class.
-
CPrivate members of the base class become private members of derived class.
-
DPublic members of the base class become public members of derived class.
Answer
Correct Answer: Public members of the base class become private members of derived class.
Explanation
Introduction / Context:Access conversion during inheritance is a subtle but important part of C++. With private inheritance, the intent is often to implement in terms of, rather than to expose an “is-a” relationship. Understanding how base-class access levels map into the derived class’s interface avoids surprises and preserves encapsulation.
Given Data / Assumptions:
- We consider a declaration like class D : private B { … };
- We focus on the visibility of B’s members through D’s interface.
- Private members of B are never directly accessible to D regardless of inheritance mode.
Concept / Approach:
Under private inheritance, B’s public and protected members become private within D. That means clients of D cannot access B’s public API through a D object unless D explicitly re-exposes selected members (e.g., via using-declarations or forwarding functions). Private members of B remain inaccessible in D in all inheritance modes; they are part of B’s internal implementation.
Step-by-Step Solution:
Map base public/protected → derived private under private inheritance. Note base private → still inaccessible from D. Conclude correct option: base public becomes derived private. Recognize that public inheritance would preserve public access instead.Verification / Alternative check:
Create B with a public method and derive D privately. Attempt to call the method via D from non-friend code; it fails. Add using B::method; inside D to re-expose it; the call then succeeds, illustrating the mapping.
Why Other Options Are Wrong:
A: protected is not the result of private inheritance.
C: base private never becomes accessible.
D: public → public occurs only with public inheritance.
Common Pitfalls:
- Using private inheritance where composition would be clearer (“has-a” vs “is-a”).
- Forgetting to re-expose necessary members when adopting private inheritance.
Final Answer:
Public members of the base class become private members of derived class.