What is the output of the following C++ program? #include <iostream> using…
20232023
What is the output of the following C++ program?
#include <iostream>
using namespace std;
class P {
public:
void print()
{ cout << " Inside P::"; }
};
class Q : public P {
public:
void print()
{ cout << " Inside Q"; }
};
class R : public Q {
};
int main(void)
{
R r;
r.print();
return 0;
}- A.
0
- B.
Error
- C.
Inside Q
- D.
Inside P
Attempted by 5 students.
Show answer & explanation
Correct answer: C
Concept
When a derived class does not define a member function itself, calling that function through an object of the derived class is resolved through name lookup: the compiler searches the derived class first, then its own immediate base class, then that base's own base, and so on, stopping at the very first class along this chain that defines a matching function. This lookup is a compile-time (static) process based on the object's declared type, independent of whether the function happens to be declared virtual.
Application
Class R publicly inherits from Q, and R itself declares no print() function, so a call r.print() cannot be resolved inside R and the search moves up to R's own base class.
R's own base class is Q (not P) - the search checks Q next, and Q does declare its own print() function that outputs " Inside Q".
Because a matching definition is already found at Q, the search stops there; it never continues on to check P, even though class P also defines a print() function.
The program is fully valid C++ - a derived class providing its own version of a function already present in an ancestor class name-hides it, which is a legal pattern for a compile-time-resolved (non-virtual) call, so no compilation error occurs.
Executing r.print() therefore invokes the version found at Q, and the program prints its " Inside Q" text before returning 0.
Cross-check
As a sanity check, if class Q did not define its own print() at all, the same rule would make the search continue past Q to P, and the output would instead come from P's definition - confirming that it is specifically Q supplying its own print() that determines which class's output is produced here, consistent with the 'nearest definition along the chain' rule stated above.