I am bit confused with the use of destructor. Please can someone clarify my doubt?
Compiler automatically creates a destructor, if it is not explicitely written in the code. Then why should we write it, when it is being automatically done by the compiler?
Because the default destructor is too simplistic.
Suppose you have a class:
1 2 3 4 5
class A{
int a;
std::string b;
B c;
};
The default destructor will call the destructors of A::b and A::c. And that's fine, but if the class looks like this:
1 2 3 4 5
class A{
int a;
std::string *b;
B *c;
};
the default destructor doesn't follow pointers, so if *A::b and *A::c were created by A, a memory leak will be created.
In this case, you should write you own destructor that does follow pointers (or not):
The node should only free its own data. Its an error for a node to try to free its neighbors.
The list object should free whatever node it has access to until there are no more nodes in the list.