Why virtual constructors are not there in C++ while we have vitual destructors?

Showing Answers 1 - 1 of 1 Answers

Sandeep Godbole

  • May 4th, 2006
 

virtual destructor become meaningful when ur deleting an object of derived class associated with the pointer of base class. For ex. if A is base and B is derived and if we write expr. A *pa = new B and delete pa, we observe that destructor of derived class is not called. Compiler recognize pa as pointer of base and bothers to place call only to destructor of base. Now that could result into some serious problem. For ex. if class B holds some pointer to which we have dynamically allocated some space. Now its a standard practice to delete such allocations in destructor. Now if the destructor itself is not called in that case it would lead to memory leackage. Declaring base class destructor as virtual ensures call is placed to derived. Hence we need to have virtual destructor. There is no need to have virtual constructor as because when u write A *pa = new B a call to both i.e. constructor of A as well as B is placed by compiler. There is no call missed out. Hence no need of virtual constructor. However a concept called virtual constructor still exist, not in the form as applying virtual to constructor but something differently. More on that on request.

  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