Search code examples
c++binary-search-tree

Can someone explain why my function is "out of scope"?


I am writing a Binary Search Tree class, but am running into a strange issue. In my code below, I have a function that I have called inorderHelper. I also have a function that overloads the insertion operator (<<). I would like to call the inorderHelper function from inside of my insertion operator function, but am getting an error when I compile, stating that inorderHelper was not declared in scope.

void BinTree::inorderHelper(Node *startNode) const{
    if (startNode != nullptr){
        inorderHelper(startNode->left);
        cout << startNode->data;
        inorderHelper(startNode->right);
    }
}

ostream& operator<<(ostream& out, const BinTree& T){
    inorderHelper (T.root); //This is the line where I am told that `inorderHelper` is not declared in this scope.
}

I think that the problem might have to do with how I have defined my inorderHelper function. Because it is a private member function, my friend function (the insertion function) cannot call it. Is that correct of me to assume?


Solution

  • The operator<< is outside your class. Since you have made this function as a friend, you will be able to use the private functions of "an object". But in your code, you are not using an object of BinTree while calling the function "inorderHelper".

    If you are trying to call the "inorderHelper" function of object "T", you have to call like T.inorderHelper(T.root).