C++ composition vs. base construction: what does this derived constructor print when it calls Show() on its own member? #include<iostream.h> class CuriousTabBase { int x, y; public: CuriousTabBase(int xx = 10, int yy = 10) { x = xx; y = yy; } void Show() { cout<< x * y << endl; } }; class CuriousTabDerived : public CuriousTabBase { private: CuriousTabBase objBase; public: CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx, yy) { objBase.Show(); } }; int main() { CuriousTabDerived objDev(10, 20); return 0; }

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