Ankit Singh

Total Post:13

Posted by  Ankit Singh
 1112  View(s)
Rate this:
  1. Ankit Singh


    What is virtual constructors/destructors?

    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-27-2018 06:31:19 AM



Enter your email address here always to be updated. We promise not to spam!