Interview question about virtual functions in C++

Vijay picture Vijay · Jun 16, 2010 · Viewed 9.3k times · Source

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?

Answer

Alan picture Alan · Jun 16, 2010

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();