What is the output of the following C++ program?
#include <iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout << "Base";
}
};
class Derived : public Base {
public:
void display() override {
cout << "Derived";
}
};
int main() {
Derived d;
Base* ptr = &d;
ptr->display();
return 0;
}
Options
-
A.
Base
-
B.
Derived
-
C.
Compilation error because Base is abstract
-
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 BExplanation:The function display() is virtual in Base and overridden in Derived. The base pointer points to a Derived object, so runtime polymorphism invokes Derived::display(). The output is
Derived. Note that Base is not abstract in this example.