C++ composition vs. base construction: what does this derived constructor print when it calls Show() on its own member?\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)\n {\n objBase.Show();\n }\n};\nint main()\n{\n CuriousTabDerived objDev(10, 20);\n return 0;\n}

Difficulty: Medium

Correct Answer: The program will print the output 100.

Explanation:


Introduction / Context:
This question examines the difference between base-class construction and member-object construction in a derived type. The derived object has a base subobject constructed with user arguments and a separate member objBase constructed by its own constructor (defaulted here).


Given Data / Assumptions:

  • Base subobject of CuriousTabDerived is built with (10, 20).
  • Member objBase has no explicit initializer, so it uses CuriousTabBase() with defaults (10, 10).
  • The body calls objBase.Show(), not the base subobject's function.


Concept / Approach:
Default construction of objBase sets x=10, y=10. The call objBase.Show() multiplies those values, printing 100. The separate base subobject constructed with (10,20) is unrelated to the objBase member being printed.


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


Verification / Alternative check:
If the member were initialized as objBase(10,20), the program would print 200 instead, proving which object is printed.


Why Other Options Are Wrong:
200 would require initializing objBase with (10,20); “Garbage” and compile-time error have no basis as all members are properly constructed.


Common Pitfalls:
Confusing the derived class's base subobject with its composed member object; overlooking default constructor arguments.


Final Answer:
100

More Questions from Objects and Classes

Discussion & Comments

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