Do I need destructor here?

If I have created destructor for node do I also have to create destructor for binary_tree to delete root?
In case I have to create it what I think I should do, would it recursively delete all the nodes in the tree or I have to travel the tree to delete every node?
1
2
3
4
5
6
7
8
9
10
11
struct node{

node* left;
node* right;

//...
~node(){
    if(left) delete left;
    if(right) delete right;
}
};


1
2
3
4
5
struct binary_tree{

node* root;
// ...
};
Yes you will have to add a destructor to the binary_tree class otherwise the node objects will not be deleted. You only need to delete the root node. The node destructor will take care of the rest.

You don't need to check if the pointer is null before deleting. Using delete on a null pointer is perfectly safe and will do nothing.
Last edited on
If I have created destructor for node do I also have to create destructor for binary_tree to delete root


Whether or not node has destructor has nothing to do with whether or not you should delete the root member, since root is a pointer-to-node and not a node. binary_tree requires a destructor.

In case I have to create it what I think I should do, would it recursively delete all the nodes in the tree or I have to travel the tree to delete every node?
binary_tree::~binary_tree() { delete root; } should be sufficient.
Tnx you guys for nice info!
Topic archived. No new replies allowed.