Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A constructor cannot be virtual

In one of the C++ tutorials in internet, i found out the below description on why a constructor cannot be virtual

We cannot declare a virtual constructor. We should specify the exact type of the object at compile time, so that the compiler can allocate memory for that specific type.

Is this description correct ?

I am getting confused particularly with the phrase: so that the compiler can allocate memory for that specific type.

like image 832
nitin_cherian Avatar asked Dec 14 '11 15:12

nitin_cherian


2 Answers

As Bjarne himself explains in his C++ Style and Technique FAQ:

A virtual call is a mechanism to get work done given partial information. In particular, "virtual" allows us to call a function knowing only an interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the exact type of what you want to create. Consequently, a "call to a constructor" cannot be virtual.

like image 69
Alok Save Avatar answered Oct 23 '22 14:10

Alok Save


The constructor cannot be virtual because the standard says so.

The standard says so because it wouldn't make sense. What would a virtual constructor do?

Virtual methods are used in polymorphism... how should polymorphism work if you don't even have the objects yet?

We should specify the exact type of the object at compile time, so that the compiler can allocate memory for that specific type.

We should specify the exact type at compile time because we want an object of that type... I found their description very confusing too.

Also, in the paragraph it doesn't say this is the reason why constructors can't be virtual. It explains why virtual methods shouldn't be called from the constructor, but that's about it.

like image 22
Luchian Grigore Avatar answered Oct 23 '22 16:10

Luchian Grigore