Why we cant use constructor with virtual functions

Showing Answers 1 - 4 of 4 Answers

The Virtual term tends to be overridable.Whenever in base class function written with virtual can only be overriden. Also the signature including function name and parameters must be same for virtual functions.

While this is not possible with constructors because constructors have same name as class,and no two constructors of base-derived classes can have same name.

And the other reason is, Constructors are special method that gets called automatically unlike other methods.

Even if i'll instantiate an object of derieved class,base class constructor get invoke first then only derieved one.

So while instatiating object of base or derieved will fire base constructor. That's why we can't use constructor as a virtual function.

  Was this answer useful?  Yes

vmmusthafa

  • Nov 17th, 2006
 

constructor is with respect to base class

  Was this answer useful?  Yes

Dharma

  • Nov 28th, 2006
 

Hi bjal,Virtual constructors are still logically valid though we cannot have them.Virtual functions does not need to have same prototype always. Virtual destructors do not have same name. Also, they too will be called implicitly like constructors.I feel that, virtual constructor concept itself is not needed anywhere. That's why we can not have them.

  Was this answer useful?  Yes

Jayanta Raychowdhury

  • Nov 29th, 2006
 

The answer is when instantiating an object compiler needs a correct object type. If the constructor is declared virtual then the the object type can not be resolved at compile time, and that's why it is not possible to declare a constructor as virtual. But we can call a constructor within a virtual function in the base class to make it look virtual.

  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