C++: Calling a Virtual Function From a Constructor is not Polymorphic

C++: Calling a Virtual Function From a Constructor is not Polymorphic

  • Comments 1

In C++, if you call a virtual function form a constructor, it won’t be polymorphic, meaning that the following code won’t behave as you may have expected:

class Foo {
public:

   
Foo() {
       
whoAmI();
   
}

   
virtual void whoAmI() {
       
cout << "Foo::whoAmI()" << endl;
   
}
};

class Bar : public Foo {
public:

   
Bar() {
       
whoAmI();
   
}

   
virtual void whoAmI() {
       
cout << "Bar::whoAmI()" << endl;
   
}
};

int main() {
   
Bar bar;
}

This would print:

Foo::whoAmI()
Bar::whoAmI()

Not:

Bar::whoAmI()
Bar::whoAmI()

The explanation lies with the order of initialization; The base class is initialized first, hence the base class’s constructor is called first, and when it calls the virtual function, the members in the derived class are not initialized yet. By enforcing that, C++ prevents you from accessing members in the derived class that are not initialized yet!

Leave a Comment
  • Please add 4 and 4 and type the answer here:
  • Post
  • If you add a "ref" to each class; the behaviour is as expected (virtual function are then called as expected ;) )

Page 1 of 1 (1 items)