Home > DeveloperSection > Interviews > What is virtual constructors/destructors?

Posted on    January-15-2015 10:20 PM

 .NET C# 
 1 Answer(s)
  695  View(s)
Rate this:

Ankit Singh

Total Post:15

Posted on    January-15-2015 11:20 PM

Virtual Constructors & Destructors

In C++ you can have virtual destructors but NOT virtual constructors. This is because when an object has virtual functions it must have an associated v-table which keeps track of the addresses to the virtual functions for that class. That would mean that an object must be instantiated firstly before a v-table for that object could exist. Since constructors are intended to instantiate and create the object there can be no virtual constructor. 

On the other hand a virtual destructor is allowed and should be used when ever there are virtual methods in the base class. The misuse of virtual destructors can lead to memory leaks and bad side effects

If the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.- Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.

Modified On Mar-28-2016 04:32:20 AM

Don't want to miss updates? Please click the below button!

Follow MindStick