Will deleting a structure's pointer also delete pointers within the structure?
Asked Answered
S

2

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

Stipulation answered 10/4, 2012 at 0:47 Comment(0)
R
10

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

Ritornello answered 10/4, 2012 at 0:49 Comment(3)
So you can implement a destructor for a structure?Stipulation
@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.Ritornello
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.Undermost
C
1

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

Causeuse answered 10/4, 2012 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.