Search code examples
c++default

Set default parameter to nullptr and non-static class fields in C++


I am building a binary search tree and the following is the add function:

void BinaryTree::add(int value, Node*& node, Node*& parent) {
    if(!node) {
        node = new Node(value);
        node->parent = parent;
    }
    else if(node->key < value)
        this->add(value, node->rightNode, node);
    else if(node->key > value)
        this->add(value, node->leftNode, node);
}

I want to set default parameters for the last two (node, parent) parameters:

void add(int value, Node*& node = root , Node*& parent = nullptr);

where root is a field of the class.

This does not seem to work for either case. How shall I implement it and what is wrong here? Thanks!


Solution

  • You can't initialize references to nullptr. They has to be valid objects. To make root defualt object you may add new function with same name

    void BinaryTree::add(int value) {
        Node* emptyParent = nullptr;
        add(value, root, emptyParent); 
    }