0

I'd like to know what's the correct way to implement virtual destructors when dealing with multilevel inheritance.

So let me introduce this simple example:

#include <iostream>

using namespace std;

struct A {

  virtual ~A() { cout << "~A()" << endl; }

};

struct B : A {
  ~B() { cout << "~B()" << endl; }
};

struct C : B {
  ~C() { cout << "~C()" << endl;  }
};

struct D : B {
  ~D() { cout << "~D()" << endl; }
};

int main() {
  A* a = new C();
  B* b = new D();
  delete a;
  delete b;
}

So afaik, when the base class declares its destructor as virtual it will call correctly the destructor of its children when it gets deleted. My concern is that when I ran this code in both cases delete a and delete b, the children were destroyed correctly, while I was spectating that only delete a would achieve that.

Is this the correct behavior? If so, does it mean that every child class of A will declare its destructor as virtual even if it's not explicitly specified and I can safely assume they will be deleted correctly?

Gerard097
  • 805
  • 4
  • 12
  • 3
    (I hope that's what you're asking) Once a function is `virtual`, you cannot make it non-`virtual` anywhere in the inheritance tree. This is especially important for destructors : if only `B`'s destructor was allowed to run, `A` would never be able to clean up its own stuff. – Daniel Kamil Kozar Mar 29 '19 at 23:10
  • Alright, thanks I wasn't sure about that. – Gerard097 Mar 29 '19 at 23:15
  • Also, when writing new code, please [refrain from using new and delete](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new). – Daniel Kamil Kozar Mar 29 '19 at 23:15
  • Ikr, but currently I'm working with Qt so I don't really have other options. – Gerard097 Mar 29 '19 at 23:18
  • Like they said, there's no need to put `virtual` again. But it's good practice to do so with every virtual function and preferably if it's C++11 onwards to put `override`. – Mirko Mar 29 '19 at 23:27
  • 1
    FWIW, Qt does not prevent you from using `unique_ptr`. Not for the GUI hierarchy itself, but all other objects. – spectras Mar 29 '19 at 23:29
  • A virtual function (destructor included) means that the **object type** will be used to determine what to call. A non-virtual function uses the **variable type** to determine what function to call. If you inherit from something with a virtual function, then you have that same virtual function. – xaxxon Mar 29 '19 at 23:40

0 Answers0