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 constr开发者_JS百科uctor, 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?
Virtual constructor Fully Explained As the virtual constructor or any constructor is called automatically just after the creation of object or we can say it is the guaranteed first function that will run in the life-cycle of the object. Also Virtual function is needed when we are in the need of binding the base class pointer to derived class object and this is done through late binding which is achieved at runtime but the constructor is bond at compile time to confirm that there is need of creation of default constructor or not. Also, to late binding there is need of virtual pointer which is not created at compile time.
精彩评论