Is it good practice to override
destructors? Why or why not?
Example:
class Foo : Base
{
public:
~Foo() override {}
};
Whenever you are dealing with inheritance, you should make any explicit destructors virtual. As with normal virtual member functions, if a base class function is virtual, all derived overrides will be considered virtual regardless of whether they are specified as such.
Yes, it is possible to override the destructor of a class. In fact, when you define a class hierarchy in which polymorphism is used, you must declare a virtual destructor in the base class.
Virtual keyword for destructor is necessary when you want different destructors should follow proper order while objects is being deleted through base class pointer.
A destructor cannot be overloaded or inherited. The static classes cannot have any destructors. An abstract class can also have destructors but we cannot create objects of an abstract class.
struct Base {
virtual ~Base() {}
};
struct Foo : Base {
~Foo() override {}
};
this compiles.
struct Base {
~Base() {}
};
struct Foo : Base {
~Foo() override {}
};
this does not.
struct Base {
~Base() {}
};
struct Foo : Base {
virtual ~Foo() {}
};
This compiles.
Live example.
If your goal is to state in Foo
that you expect Base
to have a virtual
destructor, the simplest way to do it is with the override
keyword on ~Foo
. As the semantics of deleting a Foo*
through a Base*
change significantly depending on if ~Foo
is virtual
, this may be useful to some people.
Others may be offended by using the term override
to refer to this situation.
Determine if people being offenced by using override
is more, or less important than being able to state in Foo
that Base
has a virtual destructor, so deleting an instance of Foo
via a pointer to Base
is defined behavior. I cannot make that decision for you.
As @HowardHinnant has stated in the comments, there are consequences to adding an explicit destructor; if you do so, follow the rule of 5 and either =default
, =delete
or implement the copy/move object construct/assignment operators.
It may be easier to static_assert
that Base
has a virtual destructor, unless you need the destructor for some other reason.
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