Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter - pointer or reference to a pointer?

Tags:

c++

void DeleteChildren(BSTNode *node)
{
    // Recurse left down the tree...
    if(node->HasLeftChild()) DeleteChildren(node->GetLeftChild());
    // Recurse right down the tree...
    if(node->HasRightChild()) DeleteChildren(node->GetRightChild());

    // Clean up the data at this node.
    node->ClearData(); // assume deletes internal data

    // Free memory used by the node itself.
    delete node;
}

// Call this from external code.
DeleteChildren(rootNode);

This function is deleting BST recursively.

I got a question about the first line, BSTNode *node , should I modify it to be BSTNode *& node ?

like image 892
Josh Morrison Avatar asked Sep 18 '26 12:09

Josh Morrison


1 Answers

The only time you'd want to pass a pointer by reference is if you want to change what the pointer is pointing to. If you wanted to, say, set the nodes to NULL after deleting them, then you would need to pass as BSTNode*&.

like image 150
Bradley Swain Avatar answered Sep 21 '26 05:09

Bradley Swain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!