No Virtual constructors but virtual destructor

Parag picture Parag · Mar 29, 2012 · Viewed 20.6k times · Source

If we dont have virtual constructors then why we have virtual destructors? Can constructors also be virtual?

Answer

amit picture amit · Mar 29, 2012
  • There is no point in virtual constructor - you declare exactly what type is created, and it is well known in compile time. The compiler do not need [and actually cannot, since the dynamic dispatch is based on information which is created only after the object was created]. So there are no virtual constructors.
  • Virtual destructors are important to prevent memory leaks, and monitor the system. Assume you have A* a = new B; [B inherits from A], and you later delete a; - the compiler has no way of knowing a is a B [in the general case], and will invoke A's destructor - if it wasn't virtual, and you might get a memory leak, or other faults.
  • Using virtual destructor - you ensure that B's destructor is invoked, since a B object is being destroyed.