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

using namespace std;
class B {
   public: B() {
   virtual void s() {
      cout << "Base" << endl;

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

int main() {
   D de;