How to call a virtual function inside constructors in C++?


Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. This is because the virtual function you call is called from the Base class and not the derived class.

In C++ every class builds its version of the virtual method table prior to entering its own construction. So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once the Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation. So for example, If you have the code −

Example

#include<iostream>
using namespace std;

class Base {
public:
   Base() { f(); }
   virtual void f() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
   Derived() : Base() {}
   virtual void f() { std::cout << "Derived" << std::endl; }
};

int main() {
   Derived d;    
   return 0;
}

Output

This will give the output −

Base

Updated on: 24-Jun-2020

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements