C++虚析构函数

#include<iostream>
#include<string>
using namespace std;
class Base {
public:
	 virtual ~Base(){//基类的析构函数通常应该定义成虚函数
		cout<<"~Base()"<<endl;
	}

};


class Derived : public Base {
public:
	~Derived(){
		cout<<"~Derived()"<<endl;
	}
};


int main() {
	cout<<"test 1:"<<endl;
	Derived* pointer=new Derived;
	delete  pointer;//调用基类和派生类的析构函数

	cout<<"test 2:"<<endl;
	Base* pointer2=new Derived;//动态绑定
	delete pointer2;//调用基类和派生类的析构函数,但如果基类的析构函数不是虚析构函数,则不会调用派生类的析构函数

	cout<<"test 3:"<<endl;
	Base* pointer3=new Base;
	delete pointer3;//调用基类析构函数

	system("pause");
	return 0;
}

虚析构函数机制使得基类指针被delete时能调用相应的析构函数

C++虚析构函数_第1张图片

你可能感兴趣的:(C++虚析构函数)