What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function.
CPP
#include <iostream> using namespace std; class Base { public : void print() { cout << "Base class print function \n"; } void invoke() { cout << "Base class invoke function \n"; this -> print(); } }; class Derived: public Base { public : void print() { cout << "Derived class print function \n" ; } void invoke() { cout << "Derived class invoke function \n"; this -> print(); } }; int main() { Base *b = new Derived; b -> invoke(); return 0; } |
Output:
Base class invoke function Base class print function
Since there is no virtual function, run time polymorphic behavior doesn’t work in the above code. Now predict the output of the following C++ program.
CPP
#include <iostream> using namespace std; class Base { public : virtual void print() { cout << "Base class print function \n"; } void invoke() { cout << "Base class invoke function \n"; this -> print(); } }; class Derived: public Base { public : void print() { cout << "Derived class print function \n" ; } void invoke() { cout << "Derived class invoke function \n"; this -> print(); // called under non - virtual function } }; int main() { Base *b = new Derived; b -> invoke(); return 0; } |
Output:
Base class invoke function Derived class print function
So polymorphic behaviour works even when a virtual function is called inside a non-virtual function. The output can be guessed from the fact that the function to be called is decided at run-time using the vptr and vtable. This article is contributed by Sumit Jaiswal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...