I'll include a link to this very similar problem: C++ initial value of reference to non-const must be an lvalue The error is the same (initial value of reference to non-const must be an lvalue) but the circumstances are different. In contrast to that example, in my function the pointer DOES need to be modified. I'm writing a recursive function to add a node to a Binary Search Tree. The function is included here.
1 void BST::insert(BSTNode*& current, BSTNode*& newNode)
2 {
3 //If empty, assign
4 if (current == nullptr)
5 current = newNode;
6
7 //If less, go left
8 else if (newNode->getEng() <= current->getEng())
9 insert(current->getLeft(), newNode);
10
11 //If greater, go right
12 else
13 insert(current->getRight(), newNode);
14 }
I get the error on lines 9 and 13. As shown, I'm passing in both current and newNode pointers by reference, but it has no issue with newNode, only my current->getLeft()
and current->getRight()
statements. In the question I linked to, the comment was made that the error is because pass by reference should only be used when the value will be modified in the function. In the first case of current == nullptr
the value IS modified, so I'm not sure what to do.
Editing to include BSTNode class
class BSTNode
{
public:
BSTNode();
BSTNode(char, string);
void setLeft(BSTNode* newLeft) { left = newLeft; }
void setRight(BSTNode* newRight) { right = newRight; }
BSTNode* getLeft() { return left; }
BSTNode* getRight() { return right; }
char getEng() { return Eng; }
string getMorse() { return Morse; }
private:
char Eng;
string Morse;
BSTNode* left;
BSTNode* right;
};
And this is my BST class:
class BST
{
public:
BST(string fileName);
~BST();
bool isEmpty();
void addNode(char english, string morse);
void insert(BSTNode** current, BSTNode*& newNode);
//bool searchTree(char english, string& morse);
private:
BSTNode* root;
int nodeCount;
};