Bradshawboi
Bradshawboi

Reputation: 1

BST Inserting "expression must be modifiable lvalue" C++

I'm learning about BST's and I ran into this error. I originally had the Node as a struct and it worked fine when I directly accessed the left/right members. I'm trying to make Node a class and use accessor functions instead.

Edit: I'm using an interface so the return types for the getLeftChild() and getRightChild() CANNOT be changed.

Implementation for Node:

    #include "Node.h"
    #include <iostream>

    Node::Node(int dataP)
    {
        data = dataP;
        left = NULL;
        right = NULL;
    }

    Node::~Node()
    {
    }

    int Node::getData()
    {
        return data;
    }

    NodeInterface* Node::getLeftChild()
    {
    return left;
    }

NodeInterface* Node::getRightChild()
{
    return right;
}

I get this error(see title) when I try to assign address->getLeftChild() to a new Node.

Part of my adding function:

if (data < address->getData())
{
        if (address->getLeftChild() == NULL)
        {
            address->getLeftChild() = new Node(data);
            return true;
        }
        else
        {   //Something is there
            return rAdd(address->getLeftChild(), data);

        }   

}

Thanks!

Upvotes: 0

Views: 103

Answers (2)

Bradshawboi
Bradshawboi

Reputation: 1

Since I couldn't change the return types of the getLeftChild and getRightChild functions I did:

Node* temp = dynamic_cast<Node*>(address);
temp->left = new Node(data);

I made the BST class a friend to Node so it could access its members.

It looks like it's adding correctly but I just want to see if there are better ways to solve this.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254501

getLeftChild returns a copy of the node's pointer. Assigning to that won't do anything useful.

If you want to allow assignment to the node's pointer via that function, return a reference:

Node*& getLeftChild()

It might be clearer to provide a setLeftChild, or simply to expose the pointer as a public member (since you're not providing any encapsulation anyway). Or, if this is happening in a member function which has access to private members, access it as address->left.

Upvotes: 1

Related Questions