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.\n\n#include<iostream.h>\nclass CuriousTabBase {\npublic:\n int x, y;\n CuriousTabBase(int xx = 0, int yy = 0) { x = xx; y = yy; }\n};\nclass CuriousTabDerived : public CuriousTabBase {\nprivate:\n CuriousTabBase objBase; // contained, separate instance\npublic:\n CuriousTabDerived(int xx, int yy)\n : CuriousTabBase(xx), objBase(yy) {\n cout << x << " "\n << this->x << " "\n << CuriousTabBase::x << " "\n << this->objBase.x;\n }\n};\nint main(){ CuriousTabDerived objDev(11, 22); return 0; }\n\nWhat is printed?

Difficulty: Medium

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

More Questions from Constructors and Destructors

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion