Inheriting from non-virtual dtor base class



  • I lately realized that classes like "QWidget ":http://qt.gitorious.org/qt/qt/blobs/4.8/src/gui/kernel/qwidget.h do not have a virtual dtor.

    But still lot many classes are using QWidget for public inheritance.

    And if I go by the guideline of "Herb Sutter - Guideline #4 in this article":http://www.gotw.ca/publications/mill18.htm then:

    bq. A base class destructor should be either public and virtual, or protected and nonvirtual.

    So what philosophy do we have in Qt regarding public base class's dtor ?
    And what about the semi-destruction of object when deleted from base class pointer ?

    Thanks for your time.
    shashank



  • You forgot class QObject.
    Just one virtual destructor at the top of the class hierarchy.

    Little example:
    @
    #include <iostream>

    using namespace std;

    class VirtualBase
    {
    public:
    VirtualBase()
    {
    cout << "VirtualBase: ktor (+1)" << endl;
    }
    virtual ~VirtualBase()
    {
    cout << "VirtualBase: dtor (-1)" << endl;
    }
    };

    class Base: public VirtualBase
    {
    public:
    Base()
    {
    cout << "Base: ktor (+1)" << endl;
    }
    ~Base()
    {
    cout << "Base: dtor (-1)" << endl;
    }
    };

    class Derive: public Base
    {
    public:
    Derive()
    {
    cout << "Derive: ktor (+1)" << endl;
    }
    ~Derive()
    {
    cout << "Derive: dtor (-1)" << endl;
    }
    };

    int main()
    {
    Base *base = new Derive();
    delete base;

    return 0;
    

    }
    @

    Output:
    @
    VirtualBase: ktor (+1)
    Base: ktor (+1)
    Derive: ktor (+1)
    Derive: dtor (-1)
    Base: dtor (-1)
    VirtualBase: dtor (-1)
    @

    Analogues:
    @
    virtual ~QObject(); // As VirtualBase
    ~QWidget(); // As Base
    @



  • Got it! Thanks for example code. :)



  • Always happy to help on DevNet.


Log in to reply
 

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