Sunday, October 26, 2008

C++ - Why constructor method can not be virtual

In my previous post I explained the need of an virtual destructor. Today let me explain why the constructor method can not be virtual.

For this first let me explain what is a constructor method and what is the use of constructor method.

Constructor Method: Constructor is a method which is used to construct an object and/or optionally initialize its data members.

So, main use of constructor method is to construct and return the object of the class which we intend to construct.

Virtual Method: The virtual method/function is used for run time polymorphism. With the virtual method, the actual method which will be called is decided at the run time depending based upon the type of the object which is used to call the method.

Now if the constructor method was an virtual method, then the constructor which is going to be called would be decided at the run time. ie; the object which you may construct may not be the object of the class whose object you intended to create!

This is why constructor method can not be virtual.

Powered by ScribeFire.

No comments: