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;
}
-
AThe program will print the output 100.
-
BThe program will print the output 200.
-
CThe program will print the output 400.
-
DThe program will print the output Garbage-value.
-
EThe 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); memberobjBasegets(yy,yy)i.e.,(20,20). objBase.Show()printsx*yof 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