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?
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
'virtual function' means a member function where the specific implementation will depend on the type of the object it is called upon, at run-time. The compiler and run-time support of the language contrive to make this happen. The keyword 'virtual' in C++ was taken from Simula, which had impressed Bjarne Stroustrup.
Which keyword is used to declare virtual functions? Explanation: The virtual keyword is used to declare virtual functions. Anonymous keyword is used with classes and have a different meaning. The virtual functions are used to call the intended function of the derived class.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With