C++ composition with explicit member initialization: what product does Show() print for objBase(yy, yy)?\n\n#include<iostream.h>\nclass CuriousTabBase\n{\n int x, y;\n public:\n CuriousTabBase(int xx = 10, int yy = 10)\n {\n x = xx;\n y = yy;\n }\n void Show()\n {\n cout<< x * y << endl;\n }\n};\nclass CuriousTabDerived : public CuriousTabBase\n{\n private:\n CuriousTabBase objBase;\n public:\n CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx, yy), objBase(yy, yy)\n {\n objBase.Show();\n }\n};\nint main()\n{\n CuriousTabDerived objDev(10, 20);\n return 0;\n}

Difficulty: Easy

Correct Answer: The program will print the output 400.

Explanation:


Introduction / Context:
Here we compare base construction with a composed member that is explicitly initialized using constructor arguments. Only the composed member objBase is printed, not the base subobject.


Given Data / Assumptions:

  • Derived constructor: base part gets (10,20); member objBase gets (yy,yy) i.e., (20,20).
  • objBase.Show() prints x*y of the member object.


Concept / Approach:
The initializer objBase(yy, yy) sets x=20 and y=20 for the composed object. Therefore, Show() prints 20*20 = 400. The base subobject's state is irrelevant to the printed result.


Step-by-Step Solution:
1) Construct base subobject with (10,20) → not printed. 2) Construct member objBase with (20,20). 3) objBase.Show() prints 400.


Verification / Alternative check:
Change the member initialization to objBase(xx, yy); the printout would become 200, proving the dependency.


Why Other Options Are Wrong:
100 and 200 correspond to different initializations; “Garbage” and compile errors do not apply because all members are correctly constructed.


Common Pitfalls:
Assuming Show() refers to the base subobject; overlooking that member initializers run before the constructor body.


Final Answer:
400

Discussion & Comments

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