C++ (method hiding vs base call) — what happens when a derived Display() calls Display() without qualification?\n\n#include<iostream.h>\nclass Base {\n int x, y, z;\npublic:\n Base() { x = y = z = 0; }\n Base(int xx, int yy = 'A', int zz = 'B') { x = xx; y = x + yy; z = x + y; }\n void Display(void) { cout << x << " " << y << " " << z << endl; }\n};\nclass Derived : public Base {\n int x, y;\npublic:\n Derived(int xx = 65, int yy = 66) : Base(xx, yy) { y = xx; x = yy; }\n void Display(void) { cout << x << " " << y << " "; Display(); }\n};\nint main() {\n Derived objD;\n objD.Display();\n return 0;\n}\n\nChoose the correct statement.

Difficulty: Medium

Correct Answer: The program will produce the output 66 65 infinite number of times (or till stack memory overflow).

Explanation:


Introduction / Context:
This question targets name lookup and method hiding in C++. The derived class defines its own Display() that writes two values, then calls Display() again without qualification. Does it call the base or itself?


Given Data / Assumptions:

  • Derived::Display() prints x and y, then calls Display() unqualified.
  • There is a Base::Display(), but the derived function hides it for unqualified lookup.
  • Constructors initialize Base subobject and derived members to known values (x = 66, y = 65) before the first call.


Concept / Approach:
Unqualified lookup finds the nearest match in the current scope first. Since Derived declares a function named Display, an unqualified call inside Derived::Display resolves to itself, causing infinite recursion. The compiler will not implicitly resolve to Base::Display()—you must qualify it (Base::Display()) to call the base version.


Step-by-Step Solution:

First invocation prints 66 65 (derived members).Unqualified call then re-enters Derived::Display().The cycle repeats indefinitely, printing 66 65 until stack overflow or program termination.


Verification / Alternative check:
Replace the recursive call with Base::Display() to get a single line beginning with 66 65 followed by the base’s computed triple values.


Why Other Options Are Wrong:

  • Compilation error does not occur; recursion is legal.
  • Other outputs assume a base call or single execution; here the call is recursive.


Common Pitfalls:
Forgetting to qualify base calls when a derived function with the same name exists; assuming overload resolution will “find” the base automatically.


Final Answer:
The program will produce the output 66 65 infinite number of times (or till stack memory overflow).

Discussion & Comments

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