Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the recursive call to destructor made in linked list?

Tags:

c++

I was going through this blog post and came across this code.

#include <iostream>
#include <string>

using namespace std;

struct LNode {
   int data;
   LNode* next;

   LNode(int n){data = n; next = nullptr;}

   void add_to_end(int n) {
      if (next)
         next->add_to_end(n);
      else
         next = new LNode(n);
   }
   ~LNode() { cout << " I am from LNode Destructor " << endl; delete next; }
};

int main()
{   
   LNode root(1);
   root.add_to_end(2);
   root.add_to_end(3);
   root.add_to_end(4);

}

The output of this code is

 I am from LNode Destructor 
 I am from LNode Destructor 
 I am from LNode Destructor 
 I am from LNode Destructor 

For some reason I always thought I had to traverse through the linked list using some kind of while or for loop and go on deleting all the nodes that I had dynamically allocated using new. But in above code how did the destructor got called four times and how did it automatically traverse through the linked list creating this domino effect (completely deleting the allocated memory by itself ).

like image 484
pokche Avatar asked Dec 05 '22 00:12

pokche


2 Answers

This code:

~LNode() { delete next; } // destructor

If next is set to 0, NULL or nullptr nothing will happen. However if it is set to the address of the following LNode it will cause the following LNode's destructor to run. Its destructor will do the same thing causing its following LNode to be destroyed and so on until you encounter a next variable that equals nullptr.

like image 77
Galik Avatar answered Dec 06 '22 15:12

Galik


It's basically a chain.

Starting from the root node (which is the one who loses the ambit, and therefore, its deconstructor is called automatically), when calling delete next;, you are calling the deconstructor of the next element, and so on. When next is NULL, 0 or nullptr, the process will stop.

You can also add indexes to the nodes, and see by yourself the destruction order.

like image 21
Wikiti Avatar answered Dec 06 '22 15:12

Wikiti