C++ overloaded constructors and default arguments in a base class: predict what is printed when the derived object chooses the 1-arg base constructor.\n\n#include <iostream.h>\n\nclass Base\n{\npublic:\n char S, A, M;\n Base(char x, char y)\n {\n S = y - y;\n A = x + x;\n M = x * x;\n }\n Base(char, char y = 'A', char z = 'B')\n {\n S = y;\n A = y + 1 - 1;\n M = z - 1;\n }\n void Display() { cout << S << " " << A << " " << M << endl; }\n};\n\nclass Derived : public Base\n{\n char x, y, z;\npublic:\n Derived(char xx = 65, char yy = 66, char zz = 65) : Base(x)\n {\n x = xx; y = yy; z = zz;\n }\n void Display(int n)\n {\n if (n) Base::Display();\n else cout << x << " " << y << " " << z << endl;\n }\n};\n\nint main()\n{\n Derived objDev;\n objDev.Display(0 - 1); // non-zero → calls Base::Display()\n return 0;\n}\n

Difficulty: Medium

Correct Answer: A A A

Explanation:


Introduction / Context:
This example probes constructor selection with default arguments and the order of initialization in inheritance. The derived class calls Base(x) with one argument, forcing selection of the Base overload that has defaults for the remaining parameters, and then chooses which Display to invoke at runtime.



Given Data / Assumptions:

  • Derived’s initializer list uses Base(x) with a single argument.
  • Base has an overload Base(char, char y = 'A', char z = 'B') that can be called with one argument.
  • Display(0 - 1) passes a non-zero integer, so Base::Display() runs.


Concept / Approach:
With Base(x) and defaults, y becomes 'A' and z becomes 'B'. The chosen Base constructor sets S = y, A = y + 1 - 1 (thus also 'A'), and M = z - 1 ('B' - 1 → 'A'). Therefore all three printed characters are 'A'.



Step-by-Step Solution:

Call Base(x) → selects Base(char, char y = 'A', char z = 'B').Assign S = 'A'.Compute A = 'A' + 1 - 1 → 'A'.Compute M = 'B' - 1 → 'A'.Base::Display prints: A A A.


Verification / Alternative check:
If Derived called Base(x, y) or Base(x, y, z), the printed values could differ. The code as written uses the 1-argument form with defaults.



Why Other Options Are Wrong:

  • Any option not equal to A A A contradicts the explicit arithmetic on characters in the selected constructor.
  • “Garbage” would suggest uninitialized output, which is not the case for Base members.
  • Compile-time error does not occur under the assumed environment.


Common Pitfalls:
Worrying about using member x before it is assigned; while x is indeterminate when passed, the selected Base constructor ignores its value for S, A, and M because they depend only on defaulted y and z, leading to deterministic output here.



Final Answer:
A A A

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion