Thursday, January 15, 2009

Don't use a virtual function in a constructor

Virtual functions should be used until an object is fully constructed. That is because the constructor builds the virtual function table in pieces. When it is constructing the base class, the derived class virtual function table is not yet constructed. So if you call a virtual function, you are calling the virtual function of the base class not the derived class. This is worse if the base class is a pure interface, ie the virtual functions are declared as pure (ie " =0;"), because you can't call a pure function -- the pointer points to NULL and your program crashes.

No comments: