Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {}
};
like image 333
voltento Avatar asked May 12 '17 11:05

voltento


People also ask

Should you override virtual destructor?

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.

Can we override a destructor?

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.

Should I always make destructor virtual?

Virtual keyword for destructor is necessary when you want different destructors should follow proper order while objects is being deleted through base class pointer.

Can we override destructor in C#?

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.


1 Answers

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.

like image 166
Yakk - Adam Nevraumont Avatar answered Sep 30 '22 06:09

Yakk - Adam Nevraumont