Welcome to MSDN Blogs Sign in | Join | Help

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!

Published Saturday, September 05, 2009 12:59 PM by mohamedg
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: C++: Calling a virtual function from a constructor is not polymorphic

If you add a "ref" to each class; the behaviour is as expected (virtual function are then called as expected ;) )

Saturday, September 05, 2009 1:46 PM by Jochen Kalmbach

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker