In C++ (constructor selection with defaults and a derived-class initializer), what does this program print? Pay attention to which Base constructor is called and the values assigned. #include<iostream.h> class Base { public: int S, A, M; Base(int x, int y) { S = y - y; A = x + x; M = x * x; } Base(int, int y = 'A', int z = 'B') { S = y; A = y + 1 - 1; M = z - 1; } void Display(void) { cout << S << " " << A << " " << M << endl; } }; class Derived : public Base { int x, y, z; public: Derived(int xx = 65, int yy = 66, int zz = 67) : Base(x) { x = xx; y = yy; z = zz; } void Display(int n) { if(n) Base::Display(); else cout << x << " " << y << " " << z << endl; } }; int main() { Derived objDev; objDev.Display(-1); return 0; }

Difficulty: Medium

Correct Answer: 65 65 65

Explanation:


Introduction / Context:
This example explores which base-class constructor is chosen when a derived-class initializer passes a single argument and the base has two candidate constructors, one of which provides defaulted parameters. It also shows that calling Base::Display() prints the base state, not the derived members.


Given Data / Assumptions:

  • Two Base constructors: Base(int,int) and Base(int, int y = 'A', int z = 'B').
  • Derived uses : Base(x) (a single argument), and then assigns x=65, y=66, z=67 in the body.
  • Display(-1) is nonzero, so Base::Display() executes.


Concept / Approach:
With one argument supplied, overload resolution selects Base(int, int y = 'A', int z = 'B'). That constructor ignores the first parameter value in assignments and uses the defaults for y and z to compute stored values: S = y, A = y + 1 - 1, M = z - 1 with y='A' (65) and z='B' (66), yielding three 65s.


Step-by-Step Solution:

Select ctor: Base(int, int y='A', int z='B') S = 65; A = 65; M = 66 - 1 = 65 Base::Display() prints "65 65 65"


Verification / Alternative check:
If Display(0) were called, it would print derived members "65 66 67" after they are assigned in the body; but the code explicitly calls Base::Display() due to a nonzero argument.


Why Other Options Are Wrong:

  • 65 66 67: That is the derived members, not the base state printed here.
  • "A A A" / "A B C": These are character representations, not decimal numbers from the base fields.
  • Compile error: The single-argument base constructor exists thanks to defaults.


Common Pitfalls:
Assuming the member x value is used by the base. The selected base ctor ignores it and relies on defaults for assignments shown.


Final Answer:
65 65 65

More Questions from Functions

Discussion & Comments

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