Calling virtual functions inside constructors in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 04-Apr-2019 07:35:21
Advertisements