C++ composition (has-a): given a contained base-like object constructed with (10,20), what does Show() print?
#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
{
private:
CuriousTabBase objBase;
public:
CuriousTabDerived(int xx, int yy) : objBase(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.
-
EIt prints 10 and 20 on separate lines.
Answer
Correct Answer: The program will print the output 200.
Explanation
Introduction / Context:This item focuses on composition in C++. The class CuriousTabDerived contains an instance of CuriousTabBase. The member is initialized via a member-initializer list and then used.
Given Data / Assumptions:
objBaseis constructed with(10,20).Show()printsx * y.- No inheritance is involved; this is aggregation/containment.
Concept / Approach:After construction, the contained object has x=10 and y=20. Thus x * y = 200 is printed when Show() is invoked in the derived class constructor.
Step-by-Step Solution:Construct objBase with 10 and 20.Call objBase.Show().Output is 200 followed by a newline.
Verification / Alternative check:Print x and y separately to confirm values before multiplication.
Why Other Options Are Wrong:100 assumes default 10*10; garbage or errors do not apply because initialization is explicit and valid.
Common Pitfalls:Confusing composition with inheritance or overlooking the member-initializer list.
Final Answer:The program will print the output 200.