0

There is a lot discuss about virtual destructor, When to use virtual destructors?

I found that, if there exist multilevel derived (Base, Derive1, Derive2), even if there is no virtual destructor of Derive1, the destructor of Derive2 is also can be called.

#include <iostream>
using namespace std;
class Base { 
public: 
virtual ~Base() { std::cout << "Destroy Base" << std::endl; }
}; 

class Derive1 : public Base { 
public: 
~Derive1() { std::cout << "Destroy Derive1" << std::endl; } 
}; 

class Derive2 : public Derive1 {
public:
~Derive2() { std::cout << "Destroy Derive2" << std::endl; }
}; 


int main()
{
Derive1* pObj = new Derive2();
delete pObj;
return 0;
}

The output is

Destroy Derive2
Destroy Derive1
Destroy Base

I think the Derive1 class's destructor is not virtual, thus the destructor of Derived2 can not be called. But it is called. Why? Is compiler think the destrutor of Derived1 is virtual?

Thanks for your time.

Xu Hui
  • 1,213
  • 1
  • 11
  • 24
  • 5
    Same as with other virtual functions, if the function is virtual in the base, it's also implicitly virtual in all derived classes. – HolyBlackCat Oct 11 '22 at 06:52
  • 2
    At first: Derived classes *always* call the base class destructors *by definition*! And you can always call the destructor of the *most derived* class directly. A virtual destructor serves different purposes: To be able to correctly clean up an object if it is only referred to by a pointer to a base but *not* the most derived class, e.g.: `class B { ~B(); }; class D : public B { ~D(); }; D* d = new D(); delete d;` (the only way possible to delete the object) `class VB { virtual ~B(); }; class VD : public VB { ~D(); }; B* b = new D(); delete b;` (now possible *as well*, next to first variant). – Aconcagua Oct 11 '22 at 06:58
  • Some confusion here. If a destructor is reached either statically and dynamically, then all base class destructors are called, in the reverse order of construction. That differs from other virtual functions where any base class implementations are not called implicitly. – Bathsheba Oct 11 '22 at 07:05
  • your expected output does come out without virtual destructors: https://godbolt.org/z/Wrqd3efTx – Alan Birtles Oct 11 '22 at 07:27

0 Answers0