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:
show() is virtual in Base and overridden in Derived. The pointer p has type Base*, but it points to a Derived object. Runtime dispatch therefore calls Derived::show(), printing Derived.