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

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.

class A{
public:
	//Constructor
	A(){} 
	// virtual A(){} : This is wrong and no meaning of
	//making constructor vertual as it cannot be overrided
	//in child class

}
class B:public A{
	//Cannot override base class constructor
	A(){}//This is not possible

}

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.

Related Posts