다음을 통해 공유


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

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!

Comments

  • Anonymous
    September 05, 2009
    If you add a "ref" to each class; the behaviour is as expected (virtual function are then called as expected ;) )