Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
什么時(shí)候使用?
當(dāng)你通過指針刪除一個(gè)基類的派生類的實(shí)例的時(shí)候
Constructing base
Constructing derived
Destructing base
#include<iostream>
using namespace std;
class Base
{
public:
Base() {
cout << "Base class constructor" << endl;
}
~Base() {
cout << "Base class destructor" << endl;
}
private:
};
class Derival:public Base
{
public:
Derival() {
cout << "Constructing derived " << endl;
}
~Derival() {
cout << "Destructing derived" << endl;
}
private:
};
int main() {
Derival *d = new Derival();
Base *b = d;
//Base *b = new Derival();
delete b;
system("pause");
return 0;
}
output
可以看到派生類的析構(gòu)函數(shù)并沒有執(zhí)行
/*!
* \file vitualdestructor.cpp
* \date 2017/02/24 13:13
*
* \author henry
* Contact: henrytien@hotmail.com
*
* \brief
*
* TODO: long description
*
* \note
*/
#include<iostream>
using namespace std;
class Base
{
public:
Base() {
cout << "Base class constructor" << endl;
}
virtual ~Base() {
cout << "Base class destructor" << endl;
}
private:
};
class Derival:public Base
{
public:
Derival() {
cout << "Constructing derived " << endl;
}
~Derival() {
cout << "Destructing derived" << endl;
}
private:
};
int main() {
Derival *d = new Derival();
Base *b = d;
//Base *b = new Derival();
delete b;
system("pause");
return 0;
}
output--virtual
[In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.