Reputation: 936
According to the C++ standard: 5.3.5/4:
If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.
Does this apply even for something such as:
class B
{
public:
virtual void f() const = 0;
virtual void g() = 0;
};
class D : public B
{
public:
explicit D(int x) : x_ {x} {}
void f() const override;
void g() override;
private:
int x_;
};
In this case neither D nor B has anything to deallocate, so shouldn't it no longer be required to provide virtual destructors? Or is this still undefined behavior?
Upvotes: 0
Views: 113
Reputation: 36597
That statement from the standard you quote means that a sample like (using your class B
and D
)
int main()
{
B *object = new D;
delete object;
}
has undefined behaviour if B
does not have a virtual
destructor.
No exceptions to that rule.
It doesn't matter what the classes (or their member functions) do or don't do. It is the non-virtual destructor in B
that causes the delete expression (delete object
) to have undefined behaviour. No exceptions.
Upvotes: 1
Reputation: 206567
The standard doesn't make any exceptions predicated on the contents of the classes.
I would say, "Yes, you need virtual
destructors."
Upvotes: 0