Reputation: 125
I am having errors deleting the private member class called tree2
, I have tried to use "**"
, "&*"
, "*&"
but I just keep getting error after error.
header file:
class tree1
{
private:
class tree2
{
tree2*child;
tree2**child2;
int data;
};
void clear( tree2** the_root);
tree2* root;
};
I am the one who has put the clear function there.So I go in the .cpp
file and implement it this way:
void tree1::clear(tree2** TheRoot)
{
if(*TheRoot == NULL) { return; }
clear(&(*TheRoot->child1));
clear(&(*TheRoot->child2));
delete TheRoot;
TheRoot = NULL;
}
then in a function that used clear, i call it as clear(root)
or clear(&root)
or clear(*root)
or clear(&*root)
.All combinations have failed, i keep getting erros. What is the right way to delete this class ?
Upvotes: 0
Views: 60
Reputation: 2864
As it seems you want your root
-Pointer to be NULL
after deletion. That is the reason why just passing tree2*
as a parameter is not sufficient and the tree2**
is necessary.
The line delete TheRoot;
will not delete root, but a pointer to root (which was not allocated via new
in your example, thus causing some hidden error. The same problem is in the next line. You can solve this by writing delete *TheRoot; *TheRoot = NULL;
.
But since you are using C++, you can pass tree2*&
like so:
void tree1::clear(tree2*& TheRoot)
{
if (TheRoot == NULL) { return; }
clear(TheRoot->child1);
clear(TheRoot->child2);
delete TheRoot;
TheRoot = NULL;
}
and call it like clear(root);
Upvotes: 1
Reputation: 5105
It is sufficient to use just tree2
and tree2*
(pointer to a tree2
type) data types, do not use tree2**
(pointer to a pointer of ..).
Do not expect the pointed by element to be NULL
, but set the pointer value to NULL
and just check the pointer values to decide if they point to allocated memory or not.
Upvotes: 0
Reputation: 927
you need to call it with clear(&root) if you want to modify the value. In side, you do *root = null to clear it.
Upvotes: 0