Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

what is difference between destructor and virtual destructor in c++?



  • i have seen the virtual destructor in already developed project.

    virtual ~SupervisorLoginView();

    So i want to know what is difference between virtual destructor and Normal destructor in c++


  • Moderators

    Similar to virtual and non-virtual functions.

    Holding a pointer to a base class and calling a function on it calls the method of said class only. If it's virtual then a lookup is done in the virtual table to call a method of the actual object behind the pointer. For virtual destructors it works similar - the destructor is called for the actual object's class, not for the type specified by the pointer (as they may differ) if it's virtual, otherwise, you're going to get partial destruction.

    The rule of thumb is - if the class has virtual functions or the object must be destroyed through a base class pointer, then you need to make the destructor of the base class virtual.

    [edit: fixed typo SGaist]


  • Moderators

    Similar to virtual and non-virtual functions.

    Holding a pointer to a base class and calling a function on it calls the method of said class only. If it's virtual then a lookup is done in the virtual table to call a method of the actual object behind the pointer. For virtual destructors it works similar - the destructor is called for the actual object's class, not for the type specified by the pointer (as they may differ) if it's virtual, otherwise, you're going to get partial destruction.

    The rule of thumb is - if the class has virtual functions or the object must be destroyed through a base class pointer, then you need to make the destructor of the base class virtual.

    [edit: fixed typo SGaist]


Log in to reply