0

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. What's worse, delete 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?

Yuan Wen
  • 1,583
  • 3
  • 20
  • 38

1 Answers1

2

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.

Dennis
  • 3,683
  • 1
  • 21
  • 43
  • oh,you mean that if the destructor of subclass is called, then, the destructor of its base class will be called too?@Dennis – Yuan Wen Aug 18 '16 at 09:21
  • @YuanWen destruction of an object happens by calling its destructor and then destructing its members and base classes, in reverse order of construction – M.M Aug 18 '16 at 09:22
  • No matter whether the destructor of base class is virtual or not?@Dennis – Yuan Wen Aug 18 '16 at 09:23
  • 1
    @YuanWen Yes, regardless of the virtual declaration of the dtor. The virtual on the dtor allows you to delete the derived class _via_ a base class reference. – Dennis Aug 18 '16 at 09:25
  • Is there any official documentations on this topic?@Dennis – Yuan Wen Aug 18 '16 at 09:29
  • Too much to find what I need,could please say it more specifically?@StoryTeller – Yuan Wen Aug 18 '16 at 09:39
  • 2
    @YuanWen You really need to do some research yourself. There are 100's of articles on this topic on the internet, and tens of questions on SO alone that deal with this subject in some manner. A ctrl+f on the standard will show show you what you want. – Dennis Aug 18 '16 at 09:42