Tuesday, May 08, 2007

Constructors, Destructors and Virtual Functions in C++

Can I call a virtual function in a C++ constructor or destructor? The answer is - that's bad JUJU. In C++, if you call a virtual function from a constructor or destructor, the compiler calls the instance of the virtual function defined for the class being constructed (Base::Foo if called from Base::Base), not the most derived instance. This is because the vtable is not fully initialized until the most derived constructor executes i.e., the derived class is not created yet. Similarly, when you call a virtual function from a destructor, the C++ runtime calls the base class function because the derived class has already been destroyed.

No comments:

Post a Comment