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.