Yuan Wen Yuan Wen -4 years ago 89
C++ Question

If the destructor of a subclass was called, can I stop the call to the destructor of its base class?

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
. What's worse,
one object twice is wrong.

However, this code works fine in our systmem for a very long time and passes our whole test cases. Are there any other considerations in this kind of odd implementation?

So I wander, if the destructor of subclass is called, then ,no matter what happened, the destructor of base class will be called later on.

Or, after the execution of subclass's destructor, is there any way to stop the execution of base class's destructor?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download