Virtual destructors in Qt tutorial

  • As a beginner in Qt programming, I am currently doing the Qt tutorial located at that shows how to make a basic "Notepad" app.

    Under "Notepad Header File", just under halfway down the page, the tutorial describes the Notepad class destructor thus:

    "The following line declares a virtual destructor to free the resources that were acquired by the object during its life-cycle. According to the C++ naming convention, destructors have the same name as the class they are associated with, prefixed with a tilde (~). In QObject, destructors are virtual to ensure that the destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class.".

    However, the destructor is simply "~Notepad();" with nary a "virtual" in sight. This was generated by Qt during the project creation.

    Was this an error on the part of the tutorial and Qt Creator author(s) or are destructors made virtual through some kind of Qt magic? Or, are we expected to add the "virtual" keyword ourselves?



  • Moderators

    Hi, welcome to devnet.

    No, it's not an error and there's no magic, Qt or other, involved.
    In C++ any member that has a signature the same as a base virtual member is virtual with or without the keyword. In derived classes virtual is purely optional and used mainly for readability. In C++11 there's a new keyword override that has some extra features and is often used instead of (or in addition to) the extra virtual.

    The same goes for destructors too. If a class has a virtual destructor anything that inherits it has a virtual destructor, whether you make it explicit or not. As the tutorial says "In QObject, destructors are virtual (...)", so anything inheriting a QObject has a virtual destructor. Notepad class inherits QMainWindow which inherits QWidget, which inherits QObject, so its destructor is virtual implicitly.

  • Thanks, Chris, got it. I knew is was something simple. :-)


Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.