C++ composition with explicit member initialization: what product does Show() print for objBase(yy, yy)? #include 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(yy, yy) { objBase.Show(); } }; int main() { CuriousTabDerived objDev(10, 20); return 0; }

C++ Programming Objects and Classes Difficulty: Easy
Choose an option
  • A
    The program will print the output 100.
  • B
    The program will print the output 200.
  • C
    The program will print the output 400.
  • D
    The program will print the output Garbage-value.
  • E
    The program will report compile time error.

Answer

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!
More Questions from Objects and Classes
Join Discussion