Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview question about virtual functions in C++

Tags:

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?

like image 894
Vijay Avatar asked Jun 16 '10 16:06

Vijay


People also ask

What is the use of virtual function in C?

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.

Why virtual function is called Virtual?

'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 key is used to declare virtual functions?

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.


1 Answers

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

like image 185
Alan Avatar answered Sep 21 '22 12:09

Alan