Access control in inheritance: Can a derived class object access private members of its base class directly? Choose the most accurate statement.
-
ACorrect
-
BIncorrect
-
COnly with friend declarations
-
DOnly via public inheritance
-
EOnly when using protected
Answer
Correct Answer: Correct
Explanation
Introduction / Context: Encapsulation restricts how data and functions are accessed across class boundaries. Private members belong strictly to the class that declares them. The prompt tests whether a derived class object can directly access a base class’s private members, which is a frequent source of confusion for learners.
Given Data / Assumptions:
- We have a base class with private data/methods.
- A derived class inherits from that base.
- We consider direct access (e.g., obj.privateMember) rather than mediated access (e.g., via public/protected methods).
Concept / Approach: In C++/Java-like access control, private members are accessible only to the declaring class (and its friends in C++). Derived classes do not gain direct access to the base’s private section. They may interact via public or protected interface, getters/setters, or friend functions (in C++), but not by direct access.
Step-by-Step Solution:
Define Base with private: data.Define Derived : public Base.Attempt to access Base::data directly inside Derived → compile-time error.Access instead through Base’s public/protected functions, or a friend that exposes data safely (C++).Verification / Alternative check: Compilers enforce private access; adding a protected accessor in Base or making Derived a friend (C++) changes accessibility by design choice, not inheritance alone.
Why Other Options Are Wrong:
- Incorrect: States the opposite of encapsulation rules.
- Only with friend declarations: Friendship is a separate mechanism; the generic statement “cannot access” remains true without such special arrangements.
- Only via public inheritance / Only when using protected: Inheritance mode does not expose private members; protected affects member visibility to derived classes but only for protected/public members, not private.
Common Pitfalls: Assuming inheritance “opens up” private data; conflating “is-a” with “has access to everything.”
Final Answer: Correct