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.Base::Display()
, but the derived function hides it for unqualified lookup.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:
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:
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