Why we don't have Virtual Constructor when we have Virtual Destructor ?
Hi,
Is there any technical reason behind for not having a Virtual Constructor ?
Upto my knowledge it may be because, since we know the type of constructor we are calling(which implicitly says that, we know the type of object) there is no need to have Virtual keyword for constructors ?
Is my analysis correct ?
Thanks
Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?
Late binding is based on the principle that the correct function is called based on the class of the object. So calling a virtual function via a base class pointer/reference will call the correct function based on the objects real class. Likewise, destroying an object via a base class pointer will correctly call the destructor of the objects real class.
When creating a new object the object does not exist yet, so no decision can be made based on its real class.
Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?
Not only is there no need, but it doesn't make logical sense. To create an object you have to specify its type. If there were such a thing as a virtual constructor, how would you invoke it?
Re: Why we don't have Virtual Constructor when we have Virtual Destructor ?
Quote:
Originally Posted by rsodimbakam
there is no need to have Virtual keyword for constructors ?
Constructors cannot be virtual (for the reason you indicate) but you can easily introduce a virtual construction function (which can overridden in derived classes). This gives you the effect of a virtual constructor.