What happens when a virtual function is called inside a non-virtual function in C++


In this section we will discuss about interesting facts about virtual classes in C++. We will see two cases first, then we will analyze the fact.

  • At first execute the program without using any virtual function.

  • The execute the program using any virtual function under non-virtual function.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <iostream>
using namespace std;
class BaseClass {
public:
   void display(){
      cout << "Print function from the base class" << endl;
   }
   void call_disp(){
      cout << "Calling display() from derived" << endl;
      this -> display();
   }
};
class DerivedClass: public BaseClass {
public:
   void display() {
      cout << "Print function from the derived class" << endl;
   }
   void call_disp() {
      cout << "Calling display() from derived" << endl ;
      this -> display();
   }
};
int main() {
   BaseClass *bp = new DerivedClass;
   bp->call_disp();
}

Output

Calling display() from base class
Print function from the base class

From the output, we can understand the polymorphic behavior works even when a virtual function is called inside a non-virtual function. Which function will be called is decided at runtime applying the vptr and vtable.

  • vtable − This is a table of function pointers, maintained per class.

  • vptr − This is a pointer to vtable, maintained per object instance.

Updated on: 27-Aug-2020

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements