C++ composition vs. base construction: what does this derived constructor print when it calls Show() on its own member?
#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.Show();
}
};
int main()
{
CuriousTabDerived objDev(10, 20);
return 0;
}
-
AThe program will print the output 100.
-
BThe program will print the output 200.
-
CThe program will print the output Garbage-value.
-
DThe program will report compile time error.
-
EThe program will print nothing.
Answer
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
CuriousTabDerivedis built with(10, 20). - Member
objBasehas no explicit initializer, so it usesCuriousTabBase()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