What is the output of the following C++ code using virtual functions and inheritance?

#include <iostream>
using namespace std;
class Base
{
public:
    virtual void show() { cout << "Base"; }
};
class Derived : public Base
{
public:
    void show() override { cout << "Derived"; }
};
int main()
{
    Derived d;
    Base* p = &d;
    p->show();
    return 0;
}
                        

Options

  • A. Base
  • B. Derived
  • C. Compilation error
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. Derived

Detailed Explanation

Correct Answer: Option B

Explanation:
The pointer p has type Base*, but it points to a Derived object. Because show() is virtual, runtime polymorphism calls Derived::show(). The output is Derived.