Destructor

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?

Thanks in advance.
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):
1
2
3
4
A::~A(){
	delete b;
	delete c;
}
Thanks for the reply. That gave me a better understanding. :)
I have one more question. If I have two clases of this sort. Will the automatically generated destructor destroy the Node object.

What I mean is automatically generated desctructor destroy the user defined class objects?

class Node
{
int key;
};

class A{
int a;
Node b;
B c;
};
Since A::b is a Node, and not a pointer to a Node, it will be destructed with the rest of the object by the default destructor.
Last edited on
If i have a linked list. Can you please explain how will i write destructor for the list class and node class?

Thanks
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.
Topic archived. No new replies allowed.