What will be the output of the following C++ code?
class Base
{
public:
virtual void show()
{
cout << "Base";
}
};
class Derived : public Base
{
public:
void show() override
{
cout << "Derived";
}
};
int main()
{
Base *p = new Derived();
p->show();
}
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
Answer: (B) Derived
The function show() is declared as virtual in the base class.
The pointer p is of type Base*, but it points to an object of type Derived.
Because the function is virtual, C++ performs dynamic dispatch and calls the overridden function belonging to the actual object.
Therefore, Derived is printed.