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

C++Server Side ProgrammingProgramming

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 −


using namespace std;

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

int main() {
   Derived d;    
   return 0;


This will give the output −

Updated on 24-Jun-2020 06:17:10