Destructors di C ++ secara otomatis dipanggil sesuai urutan konstruksinya (Berasal dari Base) hanya ketika destructor kelas Base dideklarasikanvirtual
.
Jika tidak, maka hanya destruktor kelas dasar yang dipanggil pada saat penghapusan objek.
Contoh: Tanpa Destructor virtual
#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;
}
Keluaran
Base Constructor
Derived Constructor
Base Destructor
Contoh: Dengan Basis Destructor virtual
#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;
}
Keluaran
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Direkomendasikan untuk mendeklarasikan destruktor kelas dasar karena virtual
jika tidak, akan menyebabkan perilaku yang tidak terdefinisi.
Referensi: Destructor Virtual