Virtual Constructor

Why constructor cannot be virtual in C++?

Questions by biranchi_1986

Showing Answers 1 - 3 of 3 Answers

Justine Jose

  • Jun 29th, 2015
 

When a function is declared virtual, it tells the compiler that the type of object which invoked this function should be declared at the run time, and invoke the appropriate function based on the type of object.
Similarly, when a constructor is declared virtual, it tells the compiler that the type of object which invoke this constructor should be declared at the run time. But for creating an object, the exact type of object should be known at compile time rather than at run time. Thats why constructors are not virtual.

  Was this answer useful?  Yes

Aarish

  • Apr 20th, 2016
 

Advanced C++ | Virtual Constructor
Can we make a class constructor virtual in C++ to create polymorphic objects? No. C++ being static typed (the purpose of RTTI is different) language, it is meaningless to the C++ compiler to create an object polymorphically. The compiler must be aware of the class type to create the object. In other words, what type of object to be created is a compile time decision from C++ compiler perspective. If we make constructor virtual, compiler flags an error. In fact except inline, no other keyword is allowed in the declaration of constructor.
In practical scenarios we would need to create a derived class object in a class hierarchy based on some input. Putting in other words, object creation and object type are tightly coupled which forces modifications to extended. The objective of virtual constructor is to decouple object creation from it’s type.

  Was this answer useful?  Yes

James Thompson

  • Aug 23rd, 2016
 

Because the virtual pointer table isnt initialised till after the constructor is complete.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions