Các hàm hủy trong C ++ tự động được gọi theo thứ tự các cấu trúc của chúng (Xuất phát sau đó là Base) chỉ khi khai báo hủy lớp cơ sởvirtual .
Nếu không, thì chỉ có hàm hủy lớp cơ sở được gọi tại thời điểm xóa đối tượng.
Ví dụ: Không có Destructor ảo
#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;
}
Đầu ra
Base Constructor
Derived Constructor
Base Destructor
Ví dụ: Với cơ sở hủy diệt ảo cơ sở
#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;
}
Đầu ra
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Nên khai báo hàm hủy lớp cơ sở virtualnếu không, nó gây ra hành vi không xác định.
Tham khảo: Máy hủy ảo