0

Consider these two classes in C++11:

class A
{
    ArbitraryClass someInstance;
};

class B : public A
{

};

And consider I use B as such:

B *foo = new B;
delete foo;

As I understand, the implicit destructor of A will not be called here.

Is someInstance still destroyed under these circumstances, because it becomes "associated" as a member of B? Or do I need to declare a virtual destructor on A to automatically trigger the member's destruction?

Litty
  • 1,856
  • 1
  • 16
  • 35
  • 7
    "As I understand, the implicit destructor of A will not be called here." why do you think that? Did you try it? Without virtual destructors, the static variable type of the object will have its destructor called along with all parent types. With a virtual destructor the dynamic object type will have its destructor called along with all its parent types. – xaxxon Jan 29 '17 at 05:42
  • 1
    Good books: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Jan 29 '17 at 05:46
  • I think you're confused. You question would make more sense (as a point of understanding, not confusion), if `someInstance` were a member of `B`, and `foo` was `A*`. – WhozCraig Jan 29 '17 at 05:50
  • @xaxxon I misread the what [this answer was suggesting,](http://stackoverflow.com/a/677623/1429658) mixing up the `D` and `B` classes -- Thus my confusion, and thus the false statement. That clears everything up. – Litty Jan 29 '17 at 05:52
  • @WhozCraig Confused and apparently dyslexic. :') – Litty Jan 29 '17 at 05:53
  • @Litty it happens. I think you were shooting for the difference betwee [**this**](http://ideone.com/jKp1DC), and [**that**](http://ideone.com/4PF1tu). – WhozCraig Jan 29 '17 at 05:53

2 Answers2

6

You need a virtual destructor in a delete expression's statically known class (in your case B) if that class is different from the most derived class of the object (in your case also B). In your case those classes are the same, so you don't need a virtual destructor: everything's destroyed properly. But if you had made the pointer type A*, then you'd need a virtual destructor in A to avoid Undefined Behavior (nasal daemons and such).

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
4

How do I ensure ...

Mostly by doing nothing.

As I understand, the implicit destructor of A will not be called here.

Wrong.

Is someInstance still destroyed under these circumstances

Yes.

because it becomes "associated" as a member of B?

Because it is a member of A, and A is destroyed.

Or do I need to declare a virtual destructor on A to automatically trigger the member's destruction?

Not in the case of the code you posted, but if (as is likely) you will be using polymorphism by deleting pointers to A that could be B or other subclasses of A you should give A a virtual destructor.

user207421
  • 305,947
  • 44
  • 307
  • 483