Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual constructors

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.

like image 911
Mortalus Avatar asked Jun 11 '11 15:06

Mortalus


2 Answers

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."

like image 154
André Caron Avatar answered Oct 02 '22 21:10

André Caron


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?

like image 27
Alok Save Avatar answered Oct 02 '22 21:10

Alok Save