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;
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++.
the short answer is no, it is unsafe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With