0
votes

We know that the base class destructor is marked virtual for proper destruction of derived class instances as the base type pointers. Then what are the differences between the following derived class destructor practices?

  1. Simple destructor: ~Derived();
  2. Destructor with override: ~Derived() override;
  3. Default destructor with override: ~Derived() override = default;
  4. Virtual destructor: virtual ~Derived() override = default;

Also is there a known best practice?

1
1. and 2. are the same. override just gives you compiler checks. 3. and 4. also same. virtual is derived to child classes. It's not necessary in child classes. virtual is redundant if override is set. IMHO dont declare a destructor if you don't need it, declare a destructor with override` and default if you need a declaration and declare a destructor with override if you need a custom destructor.Thomas Sablik

1 Answers

1
votes

Primer: We expect Baseclass::~Baseclass to be virtual and class Derived to be derived public from Baseclass.

  1. Simple Destructor: That's what you will basically use if there are no other classes (and never will be) being derived from Derived. Do not declare all destructors as virtual but prefer using override keyword as described in 2. Exception: You create a shard library and want people to safely dervie classes from your library.

  2. Destructor with override: If you declare a dervied class and want to call it's base class destructor use override. That way you will get a compilation error if you forgot to add virtual to baseclass desctructor.

  3. Destructor with override and default destructor: You will also get a compilation error if you forgot to declare base class destructor virtual. Use this if you do not need to do special cleanup tasks (e.g. freeing HEAP-allocated memory). Better/cleaner then writing ~Derived() {}

  4. Combination of all: Well, there is no benefit in declaring a destructor virtual and also use override. Override will declare the method (in this case the destrcutor) as virtual anyways. See: https://en.cppreference.com/w/cpp/language/override. So it is the same as 3.