Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inheritance without virtual destructors

If the parent class's destructor is not virtual, but the subclass has no additional members, is it safe to use the parent class's destructor?

class A{
    ~A();
    protected:
        int i;
};
class B: public A{

}

A *x = new B; delete x;
like image 374
user2874988 Avatar asked Dec 21 '25 09:12

user2874988


2 Answers

It is not safe, it's undefined behaviour as per §5.3.5

5.3.5 Delete [expr.delete]

3 In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

An example of why it could break is this:

class A
{
public:
    ~A();
protected:
    int i;
};

class B: public A
{
    virtual void dummy();
}

A *x = new B; delete x;

Now B has a vtbl and hence the object layout is different.

And BTW: public class A is Java or some other language, but not C++.

like image 188
Daniel Frey Avatar answered Dec 22 '25 23:12

Daniel Frey


the short answer is no, it is unsafe.

like image 25
Zac Wrangler Avatar answered Dec 23 '25 00:12

Zac Wrangler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!