Search code examples
c++classlvalue

C++ Error: lvalue required as unary '&' operand


I have created a class named node. It is defined as follows:

class node
{
    private:
        int key;
        node * next;

    public:
        void setkey(int key);
        void setnext(node * next);
        int getkey();
        node * getnext();
};

These functions are basic getter and setter functions. Now, if I try to do this:

MoveNode(&(bTail->getnext()),&start);

it shows error as :lvalue required as unary '&' operand

Now, if I update the class Node and keep (node * next) as public and access via this:

MoveNode(&(bTail->next),&start);

It shows no error.

Please help as to how can I get rid of the error.


Solution

  • When you return node* from getnext(), you create a temporary variable of node* type, so it has no sense to take its address by using &, this temporary variable will anyway be destroyed soon.

    When you directly access next, you refer to a long-living variable, and you can take its address.

    You might want to return a reference to node* from getnext():

    node*& getnext() {return next;};
    

    so that it will point to the same variable next and you will be able to take its address.