Yuan Wen Yuan Wen - 3 months ago 14
C++ Question

Will the destructor of subclass call the destructor of its base class without condition?

I came across some odd code like the following:

class B {
int* ab;
///...
~B() { /// not virtual
delete ab;
}
///...
}

class D : public B {
int* ad;
///...
~D() {
delete ab;
delete ad;
}
///...
}


But in my opinion, the destructor of the subclass will definitely call the destructor of its base class. So, I think there is no need for the subclass to deallocate resources allocated by its base class. Thus, there is no need to add
delete ab
in the destructor of class
D
.

Are there any other considerations in this kind of an odd implementation?

Answer

You are correct that the B class destructor will be called if the a D instance is destructed. The call to delete ab; in the D dtor is a bug.

The other thing to consider with this code, is that because B's dtor is not virtual you cannot delete an instance of D via a B pointer.

The DTOR for D is incorrect in both cases though, and should definitely be changed. If you plan on using the hierarchy of classes polymorphically then you also must change the B DTOR to be virtual.

Comments