8

Assume I have a structure with two pointers each pointing to an object that has an implemented destructor. Also assume that the head points to a Listnode structure that has a non-NULL value *student and *next:

struct Listnode {    
  Student *student;
  Listnode *next;
};
Listnode *head =  new Listnode;

If I use the delete reserve word on the Listnode pointer 'head' will it call the destructors within that structures Student class and Listnode class which 'student' and 'next' point-to respectively. In other words, will deleting *head also delete *student and *next provided head was the only pointer to that Listnode

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pat Murray
  • 4,125
  • 7
  • 28
  • 33

2 Answers2

10

Not unless your destructor ~Listnode calls delete on the pointers. Calling delete will, however, invoke the destructors of non-pointer members.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • So you can implement a destructor for a structure? – Pat Murray Apr 10 '12 at 00:54
  • 2
    @PatMurray Absolutely! Whatever you can do in a class, you can do in a `struct` too. In fact, the only difference is that members of the class before the first access declaration (public, private, or protected) are considered private, while the same members of a struct are considered public. – Sergey Kalinichenko Apr 10 '12 at 00:57
  • Structs can inherit like classes, and the default inheritance access is public for struct and private for classes. Another difference, but along the same lines. – MSalters Aug 21 '15 at 14:47
1

No!you should delete them manually first, but you could also add the delete codes in the destructor method.

cloudygoose
  • 608
  • 1
  • 6
  • 16