0
votes

I understand this probably a very basic question but nevertheless if you have a really simple linked list in c++ something like this...

class link{
    link * next;
    ~link(void){
         delete next;
    }

}

If the destructor is called on the head of this linked list and its pointer to the next node is deleted does the destructor of the next node get called? Effectively would calling the destructor on the head deleted all the links in the list. Or would the rest of the list just hang there?

4
you don't need to delete next in the destructor of link.NetVipeC

4 Answers

1
votes

It is all simple. If you have a class for example link then when you create an object of this type using operator new then a constrauctor of link is called

link *node = new link;

When you delete an object created with using new then its destructor is called

delete node;

In your example next is the same object of type link (pointer to object created with operator new) as the object that holds it. So its destructor will be called when operaor delete is applied to it.

1
votes

Yes, object's destructor will be called when you delete it. Therefore, in this implementation all nodes (or links, if you prefer) after a deleted node will be also destroyed.

0
votes

yes, except, that next is private so can never be set by anything (you have no methods or friends) and if you are going to have links that derive from link the the destructor should be virtual so the correct code (rather than just link::~link is called by delete). you DO need to delete next because it is a pointer to an instance of an object. without the delete then nothing would happen (the destructor of a pointer does not delete the object it pointer to).

0
votes

Delete calls the destructor of the to-be-deleted and frees the memory afterwards. So if you have a linked list (without cycles) and delete the head, it will free the complete list.