base class 沒有把 destructor 宣告為 virtual,當 derived class 透過 base class 指標被刪除的時候,呼叫的並不是 derived class 的 destructor,而是只呼叫了 base class 的 destructor。
#include <iostream>
using namespace std;
class Base{
public:
~Base() {
cout << "base destructor" << endl;
}
};
class Derived: public Base {
public:
~Derived() {
cout << "derived constructor" << endl;
}
};
int main(int argc, const char* argv[]) {
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
return 0;
}
執行結果為:
derived constructor
base destructor
=========
base destructor
#include <iostream>
using namespace std;
class Base{
public:
virtual ~Base() { // 這裡加上 virtual
cout << "base destructor" << endl;
}
};
class Derived: public Base {
public:
~Derived() {
cout << "derived constructor" << endl;
}
};
int main(int argc, const char* argv[]) {
{
Derived d;
}
cout << "=========" << endl;
Base *b = new Derived;
delete b;
return 0;
}
執行結果為:
derived constructor
base destructor
=========
derived constructor
base destructor
...