[Effective-cpp] Item 9: Never callvirtualfunctions duringconstruction or destruction

Kevlin Henney kevlin at curbralan.com
Wed Jun 7 08:49:53 EDT 2006


Adrian Fagg <adrianf at evaluategroup.com> writes
>
>I'd say that in general the ability to call virtual functions in the
>Delphi/Java way is occasionally useful, but usually a non-issue.

Mostly agreed.

>Hence experience tells me that
>accidentally calling a virtual function in a constructor doesn't lead to any
>nasty surprises since it's an accident that doesn't happen!

Experience indicates that it does happen, more frequently than a blue 
moon but less often than some of the other exciting opportunities 
available in the language.

A more rational approach to class hierarchy design tends to reduce the 
likelihood of it occurring quite dramatically as the issue simply never 
arises. However, many frameworks require a common and a variable part to 
their object initialisation, and it is here, for the framework 
developers themselves, that this is most likely to bite. Better 
encapsulation of initialisation within the library -- factory methods 
and two-phase initialisation -- avoids the problem (and many others) 
completely, regardless of language.

>I believe that this is true for both rules, which does raise the question -
>why this item is in the book - do people really come unstuck as a
>consequence of this or is it just a tricky interview question?

It is many things: a tricky interview question, a frequently reported 
"compiler bug", something that causes people to become unstuck, a topic 
for discussion on lists, a repeated item in coding guidelines and 
"effective"/"how to" books, etc.

Kevlin
-- 
____________________________________________________________

   Kevlin Henney                   phone:  +44 117 942 2990
   mailto:kevlin at curbralan.com     mobile: +44 7801 073 508
   http://www.curbralan.com        fax:    +44 870 052 2289
   Curbralan: Consultancy + Training + Development + Review
____________________________________________________________




More information about the Effective-cpp mailing list