Calling virtual functions inside constructors in C++


Virtual functions calling from a constructor or destructor is dangerous and should be avoided whenever possible as the virtual function we call is called from the Base class and not from the derived class.

The reason is that in C++ Super-classes are constructed before derived classes. So, in the following example, as B must be instantiated, before D is instantiated. When B's constructor is called, it's not D yet, so the virtual function table still has the entry for B's copy of s().

Example Code

 Live Demo

#include<iostream>
using namespace std;
class B {
   public: B() {
      s();
   }
   virtual void s() {
      cout << "Base" << endl;
   }
};

class D: public B {
   public: D() : B() {}
   virtual void s() {
      cout << "Derived" <<endl;
   }
};

int main() {
   D de;
}

Output

Base

Updated on: 30-Jul-2019

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements