当在c++中覆盖一个类(使用虚析构函数)时,我在继承类上再次实现了虚析构函数,但我需要调用基析构函数吗?
如果是这样的话,我想应该是这样的……
MyChildClass::~MyChildClass() // virtual in header
{
// Call to base destructor...
this->MyBaseClass::~MyBaseClass();
// Some destructing specific to MyChildClass
}
我说的对吗?
c++中的析构函数只有在基类析构函数声明为虚时才会自动按其构造的顺序(先派生后基)调用。
如果不是,则在删除对象时只调用基类析构函数。
示例:没有虚析构函数
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout << "Base Constructor \n";
}
~Base(){
cout << "Base Destructor \n";
}
};
class Derived: public Base{
public:
int *n;
Derived(){
cout << "Derived Constructor \n";
n = new int(10);
}
void display(){
cout<< "Value: "<< *n << endl;
}
~Derived(){
cout << "Derived Destructor \n";
}
};
int main() {
Base *obj = new Derived(); //Derived object with base pointer
delete(obj); //Deleting object
return 0;
}
输出
Base Constructor
Derived Constructor
Base Destructor
示例:使用基本虚析构函数
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout << "Base Constructor \n";
}
//virtual destructor
virtual ~Base(){
cout << "Base Destructor \n";
}
};
class Derived: public Base{
public:
int *n;
Derived(){
cout << "Derived Constructor \n";
n = new int(10);
}
void display(){
cout<< "Value: "<< *n << endl;
}
~Derived(){
cout << "Derived Destructor \n";
delete(n); //deleting the memory used by pointer
}
};
int main() {
Base *obj = new Derived(); //Derived object with base pointer
delete(obj); //Deleting object
return 0;
}
输出
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
建议将基类析构函数声明为虚值,否则会导致未定义的行为。
参考:虚析构函数