Search code examples
c++virtual

Interview question about virtual functions in C++


I was asked this crazy question. I was out of my wits.

Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object?

Is this possible?


Solution

  • If you're trying to invoke a virtual method from the base class pointer, yes.

    That's polymorphism.

    If you're asking, with a base class pointer to a derived class, can you invoke a base class method that is overriden by the derived class? Yes that's also possible by explicitly scoping the base class name:

    basePtr->BaseClass::myMethod();