C++ (multiple inheritance-like layout: base subobject vs contained member) — trace which x is printed from a derived object with both a base x and a contained base instance.
#include
class CuriousTabBase {
public:
int x, y;
CuriousTabBase(int xx = 0, int yy = 0) { x = xx; y = yy; }
};
class CuriousTabDerived : public CuriousTabBase {
private:
CuriousTabBase objBase; // contained, separate instance
public:
CuriousTabDerived(int xx, int yy)
: CuriousTabBase(xx), objBase(yy) {
cout << x << " "
<< this->x << " "
<< CuriousTabBase::x << " "
<< this->objBase.x;
}
};
int main(){ CuriousTabDerived objDev(11, 22); return 0; }
What is printed?
-
A11 22 0 0
-
B11 11 0 22
-
C11 11 11 0
-
D11 11 11 22
-
EThe program will report compile time error.
Answer
Correct Answer: 11 11 11 22
Explanation
Introduction / Context:This question distinguishes a base subobject from a separate contained data member of the same type. It asks you to track constructor argument forwarding and to identify which x each qualified name refers to in the output expression.
Given Data / Assumptions:
- CuriousTabDerived : CuriousTabBase public, so the derived object has a base subobject with its own x.
- CuriousTabDerived also contains objBase as a separate CuriousTabBase member.
- Initializer list calls CuriousTabBase(xx) → base subobject x = xx = 11 (yy defaults 0).
- Initializer list also calls objBase(yy) → objBase.x = yy = 22 (its y defaults 0).
Concept / Approach:Unqualified x inside CuriousTabDerived refers to the base subobject’s x because there is no more-derived x member. this->x and CuriousTabBase::x refer to the same base subobject member. objBase.x is the contained member’s x, independent of the base subobject.
Step-by-Step Solution:
1) After construction: base-subobject x = 11; objBase.x = 22.2) cout chain prints, in order: 11, 11, 11, 22.3) Spaces are inserted as shown in the code.Verification / Alternative check:Make objBase(99) to see the last value change independently while the first three remain equal to xx.
Why Other Options Are Wrong:
- Options with 0s assume uninitialized or defaulted x for prints, which is incorrect given the initializer list.
- The variant with 22 in earlier positions confuses objBase with the base subobject.
Common Pitfalls:Confusing composition (has-a) with inheritance (is-a) and misreading qualified names.
Final Answer:11 11 11 22