voltento
voltento

Reputation: 887

Is it good practice to override the destructor?

Is it good practice to override destructors? Why or why not? Example:

class Foo : Base
{
public:
    ~Foo() override {}
};

Upvotes: 11

Views: 4847

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275720

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.

Upvotes: 8

Related Questions