Which statements about C++ constructors in inheritance are correct? Consider access to base members and whether constructors are inherited or callable.
-
AA constructor of a derived class can access any public and protected member of the base class.
-
BConstructor cannot be inherited but the derived class can call them.
-
CA constructor of a derived class cannot access any public and protected member of the base class.
-
DBoth A and B.
-
EConstructors are inherited like ordinary member functions.
Answer
Correct Answer: Both A and B.
Explanation
Introduction / Context:Understanding how constructors interact with inheritance is essential for designing class hierarchies. This question explores access to base members and the notion of inheriting or invoking base constructors.
Given Data / Assumptions:
- Standard C++ access control: public, protected, private.
- Derived classes initialize their base subobjects via constructor initializer lists.
- We consider the classic rule that constructors themselves are not inherited as callable functions on the derived type (ignoring using-inheritance syntax details).
Concept / Approach:Derived member functions, including constructors, may access base public and protected members subject to access rules. Constructors are not inherited as ordinary members; instead, a derived constructor explicitly invokes a chosen base constructor in its initializer list. Therefore, statements A and B are correct together, while claiming no access or full inheritance of constructors is wrong.
Step-by-Step Solution:1) Access: within Derived::Derived(), you can read/write Base's protected/public members.2) Invocation: Derived::Derived(args) : Base(base_args) { /.../ }3) There is no syntax to “inherit” constructors as ordinary callable functions (though using Base::Base in modern C++ inherits constructors for overload set construction, not as general callables).4) Therefore, pick “Both A and B.”
Verification / Alternative check:Create a Base with protected data and a Derived constructor that initializes it via Base’s constructor; compilation succeeds respecting access control.
Why Other Options Are Wrong:C: contradicts access rules.E: misconstrues inheritance of constructors; they are not ordinary inherited methods.
Common Pitfalls:Forgetting to call the appropriate base constructor, leading to unintended default initialization of the base subobject.
Final Answer:Both A and B.