I was wondering what is the meaning of a virtual constructor and how would it be used.
In addition I know that C++ does not allow for a virtual constructor, and I was wondering why.
C++ does not allow virtual constructors because you need an object to invoke a virtual method in the first place!
The term virtual constructor is used for for idiom and a well-known design pattern. This idiom/pattern involves the definition of factory: an intermediate object with a virtual method who's role is to create the object in question. Because the method is virtual and it's purpose is to create an object, it is nicknamed a "virtual constructor."
There are no virtual constructors in C++ though it is possible to simulate the behavior.
Why no virtual constructors in C++?
My attempt to give a Reasoning:
The standard states that the object creation is not complete until the closing brace of the constructor. Thus a object exists only after the constructor ends.
Virtual keyword is used to implement a polymorphic behavior, where in actual function to be called is evaluated at run time, depending on the actual type of object, this
is pointing to. In order for the constructor to be dispatched using the virtual table mechanism, there has to be an completely existing object with a pointer to the virtual table, but inside a constructor the object construction itself is not complete so how can a pointer to the virtual table exist if the object isn't completely formed?
Reasoning of Dr. Bjarne Stroustrup:
Why don't we have virtual constructors?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With