Search code examples
c++polymorphismvirtual-destructorself-destruction

Lack of virtual destructor when doing "delete this"


Section 16.15 of the C++ FAQ Lite discusses delete this and then mentions:

Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.

Why is this true? Consider this code:

class ISuicidal {
public:
    virtual void suicide() = 0;
};

class MyKlass : public ISuicidal {
public:
    MyKlass() {
        cerr << "MyKlass constructor\n";
    }

    ~MyKlass() {
        cerr << "MyKlass destructor\n";
    }

    void suicide() {
        delete this;
    }
};

Used thus:

int main()
{
    ISuicidal* p = new MyKlass;
    p->suicide();
    return 0;
}

In the call p->suicide(), the destructor of MyKlass is called as expected, even though ISuicidal has no virtual destructor.

To me this makes sense, because in MyKlass::suicide, the static type of this is known to be MyKlass*, so the correct destructor is invoked. This is easy to verify by placing typeid calls inside suicide.

So is the FAQ entry inaccurate, or am I misunderstanding it?


Solution

  • You are misunderstanding. Implement the suicide function (ie delete this) in ISuicidal and you will find that when the this pointer is a base class calling delete on it doesn't call the derived class's destructor.