C++ (method hiding vs base call) — what happens when a derived Display() calls Display() without qualification?
#include
class Base {
int x, y, z;
public:
Base() { x = y = z = 0; }
Base(int xx, int yy = 'A', int zz = 'B') { x = xx; y = x + yy; z = x + y; }
void Display(void) { cout << x << " " << y << " " << z << endl; }
};
class Derived : public Base {
int x, y;
public:
Derived(int xx = 65, int yy = 66) : Base(xx, yy) { y = xx; x = yy; }
void Display(void) { cout << x << " " << y << " "; Display(); }
};
int main() {
Derived objD;
objD.Display();
return 0;
}
Choose the correct statement.
-
AThe program will report compilation error.
-
BThe program will run successfully giving the output 66 65.
-
CThe program will run successfully giving the output 65 66.
-
DThe program will run successfully giving the output 66 65 65 131 196.
-
EThe program will produce the output 66 65 infinite number of times (or till stack memory overflow).
Answer
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()printsxandy, then callsDisplay()unqualified.- There is a
Base::Display(), but the derived function hides it for unqualified lookup. - Constructors initialize
Basesubobject 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 prints66 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).