If a derived-class object has a base class with a virtual function but a non-virtual destructor, and a derived-class object is destroyed (explicitly) by applying the delete operator to a base-class pointer to the object the base-class destructor is called, rather than the derived class’s destructor
If a class has a virtual function and also a destructor, you should make the destructor a virtual function. These allows the derived class destructor to override your base class destructor, so the correct destructor will be called.
class Base {
char *array;
public:
Base() { array = new char[100]; }
~Base() { delete [] array; }
};
class Derived : public Base {
int *array;
public:
Derived() { array = new int[200]; }
~Derived() { delete [] array; }
};
int main()
{
Base *obj = new Derived;
// ...
delete obj; // only ~Base will be called. Memory leak!
return 0;
}
class Base {
char *array;
public:
Base() { array = new char[100]; }
virtual ~Base() { delete [] array; }
};
class Derived : public Base {
int *array;
public:
Derived() { array = new int[200]; }
~Derived() { delete [] array; }
};
int main()
{
Base *obj = new Derived;
// .
.
.
delete obj; // both
~Derived and then ~Base are called
return 0;
}