Explanation on why a constructor cannot be virtual based on study : Correct the mistakes if any

nitin_cherian picture nitin_cherian · Dec 15, 2011 · Viewed 17k times · Source

I did some study to find out why a constructor cannot be virtual. I am consolidating my understanding here.

I will first explain what is a virtual function and then explain why a constructor cannot be virtual based on the first explanation.

What is a virtual function ?

A virtual function is a function or a method in the base class which can be redefined or overriden in the derived class, by a function with the same signature. In other words, virtual function allows to have a customized implementation of the base class method in the derived class. It needs to be declared with the virtual keyword. At the time of virtual function invocation, the decision to choose which version of the function definition(in the base class or derived class) is made at run-time, depending on the type of the invoking object(dynamic binding).

When a function is declared virtual, it tells the compiler that the type of the object which would invoke the virtual function should be determined only during run-time. Then based on the type of the object, the function call should be bound to the function definition and the appropriate function should be invoked.

Why a constructor cannot be virtual?

When a function is declared virtual, it tells the compiler that the type of the object which would invoke the function should be determined only during run-time, and then invoke the appropriate version of the function based on the type of the object.

If the constructor were to be declared virtual, it would tell the compiler that type of object which would invoke the constructor should be determined at run-time. But for constructing an object, the exact type of object should be known at compile time rather than at run-time. This is the reason why a constructor cannot be virtual.

I would like the SO members to correct the mistakes in both the answers, if any. I think it would help me and others, if you could correct the answers by re-writing it as your answers, rather than just pointing out the mistakes.

Answer