Virtual method call in constructor

Skip to end of metadata
Go to start of metadata

What's the harm in calling a virtual method in a constructor? Well, the problem is that virtual calls always act on the most derived type. This means that, if you make a virtual call in a constructor, and the type you're on is not the most derived type, you'll end up calling it on a class whose constructor has not been run. As you can imagine, this can, in certain situations, lead to confusion and errors.

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. Dec 29, 2010

    It is often seen, that virtual call in constructor is meant to allow derived type to setup some aspect of base type. Such virtual method, in fact, should be pure function that returns some value and doesn't depend on the state of derived type. If this is the case, make such function static (since it is pure) and pass its return value to base type as parameter to protected constructor.