C++ base-class constructor vs member-object constructor: trace printed members.
#include
class CuriousTabBase {
public:
int x, y;
CuriousTabBase(int xx = 0, int yy = 0) { x = xx; y = yy; }
};
class CuriousTabDerived : public CuriousTabBase {
private:
CuriousTabBase objBase;
public:
CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx), objBase(yy) {
cout << this->x << " " << this->y << " " << objBase.x << " " << objBase.y << " ";
}
~CuriousTabDerived() {}
};
int main() {
CuriousTabDerived objDev(11, 22);
return 0;
}
-
A11 22 0 0
-
B11 0 0 22
-
C11 0 22 0
-
D11 22 11 22
-
EThe program will report compile time error.
Answer
Correct Answer: 11 0 22 0
Explanation
Introduction / Context: The problem probes constructor initializer lists for a derived class and a contained member object. It checks whether you can follow which values are passed to the base subobject versus the member subobject and how defaulted parameters are used.
Given Data / Assumptions:
- CuriousTabBase(xx = 0, yy = 0) stores x = xx, y = yy.
- CuriousTabDerived(int xx, int yy) : CuriousTabBase(xx), objBase(yy).
- Prints: this->x, this->y, objBase.x, objBase.y.
Concept / Approach: The base subobject of CuriousTabDerived receives only xx, so xx maps to x and the default yy = 0 sets base y to 0. The member object objBase(yy) receives yy as its first argument (xx), while its own second parameter defaults to 0. So objBase.x = yy and objBase.y = 0.
Step-by-Step Solution:
Construct base: CuriousTabBase(xx) → x = 11, y = 0.Construct member: objBase(yy) with yy = 22 → objBase.x = 22, objBase.y = 0.cout prints: 11 0 22 0.Verification / Alternative check: If the base initializer were CuriousTabBase(xx, yy) then this->y would be 22; if objBase were constructed as objBase(yy, yy) then objBase.y would be 22. Neither is done here.
Why Other Options Are Wrong:
- 11 22 0 0: assigns yy to base y, which does not happen.
- 11 0 0 22: swaps x/y mapping for objBase.
- 11 22 11 22: would require passing both parameters to both ctors.
- Compile error: none present.
Common Pitfalls: Forgetting that default parameters fill omitted ctor args; confusing base-subobject initialization with member-object initialization.
Final Answer: 11 0 22 0