Why virtual constructor in C++ is not possible? – Reason

(Last Updated On: February 25, 2019)

Answer includes reason why virtual constructor in C++ is not possible. By the way there is no concept of C++ virtual constructor.

Note that virtual constructor is frequently asked interview question and we need to provide the reason that why there is not concept of virtual constructor. Also, don’t forget to specify that Factory Method Design Pattern is also known as virtual constructor in Object oriented design. So, virtual constructor in c++ and factory method design pattern both are different concept.

Also not that,  there is a concept of  virtual destructor in C++ programming.

Answer: First of all, we don’t have provision of virtual constructor in C++. Having a virtual constructor is meaningless as we cannot override the constructor of a class. So, making constructor virtual has no meaning.

 

 

Secondly, the compiler generates hidden code in the constructor of each class containing virtual methods to initialize the VPTR of its objects to the address of the corresponding VTABLE. Means, constructor is responsible to assign the address of classes VTALBE into VPTR.

So, it is pretty clear that at the time, when constructor is invoked, the virtual table would not be available to lookup virtual constructor address in the VTABLE. So, it doesn’t make sense to have virtual constructor.

NOTE:

  1. When we precede the constructor with virtual keyword to make constructor virtula, compiler will flash below error. We can use only inline or explicit keyword with constructor.

                                                          Error: ‘inline’ is the only legal storage class for constructors       

  1. In C++ concept, there is no virtual constructor. In OOD(Object Oriented Design), the “factory method” design pattern is also known as virtual constructor.