C++ base-class constructor vs member-object constructor: trace printed members.\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;\npublic:\n CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx), objBase(yy) {\n cout << this->x << " " << this->y << " " << objBase.x << " " << objBase.y << " ";\n }\n ~CuriousTabDerived() {}\n};\nint main() {\n CuriousTabDerived objDev(11, 22);\n return 0;\n}\n

Difficulty: Medium

Correct Answer: 11 0 22 0

Explanation:


Introduction / Context:
The problem probes constructor initializer lists for a derived class and a contained member object. It checks whether you can follow which values are passed to the base subobject versus the member subobject and how defaulted parameters are used.


Given Data / Assumptions:

  • CuriousTabBase(xx = 0, yy = 0) stores x = xx, y = yy.
  • CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx), objBase(yy).
  • Prints: this->x, this->y, objBase.x, objBase.y.


Concept / Approach:
The base subobject of CuriousTabDerived receives only xx, so xx maps to x and the default yy = 0 sets base y to 0. The member object objBase(yy) receives yy as its first argument (xx), while its own second parameter defaults to 0. So objBase.x = yy and objBase.y = 0.


Step-by-Step Solution:

Construct base: CuriousTabBase(xx) → x = 11, y = 0.Construct member: objBase(yy) with yy = 22 → objBase.x = 22, objBase.y = 0.cout prints: 11 0 22 0.


Verification / Alternative check:
If the base initializer were CuriousTabBase(xx, yy) then this->y would be 22; if objBase were constructed as objBase(yy, yy) then objBase.y would be 22. Neither is done here.


Why Other Options Are Wrong:

  • 11 22 0 0: assigns yy to base y, which does not happen.
  • 11 0 0 22: swaps x/y mapping for objBase.
  • 11 22 11 22: would require passing both parameters to both ctors.
  • Compile error: none present.


Common Pitfalls:
Forgetting that default parameters fill omitted ctor args; confusing base-subobject initialization with member-object initialization.


Final Answer:
11 0 22 0

More Questions from Constructors and Destructors

Discussion & Comments

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