What is the output of the following C++ program?

#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:
Because show() is virtual, the call is resolved according to the actual object type at runtime. The base pointer points to a Derived object, so Derived::show() executes and prints Derived.