Virtual Constructors

Why don't we have virtual constructors in c++.
Please give me the brief discussion on this topic.
1) Objects created is stages. First, most base class is initialised, then second after it and so on to the most derived. Each of these objects does not know that it is something more than being constructed, you cannot know if you are final constructor in chain.

2) To use virtual functions you need initialized object of the derived type accessed through pointer to the base type. Notice the chicken and egg problem? You need already created object to use its virtual functions, because before that virtual table (used for dispatch) does not exist. Add to that specifics of object initialization (derived part is not initialized when base part do it work) and you will find out that you will get information needed to use virtual functions for concrete type after this type is already constructed.

3) Technical impossibilities. To overload a function you need to create function with the same name and signature. To do that for constructors is simply impossible

http://www.stroustrup.com/bs_faq2.html#virtual-ctor
Plus: the virtual table is initialized from the constructor, hence a constructor cannot be virtual itself.

This has consequences:
In a constructor you cannot call a virtual function of a derived class because the derived class constructor isn't called yet.
Last edited on
Topic archived. No new replies allowed.