Reputation: 177
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.
Upvotes: 2
Views: 3871
Reputation: 238411
MoveNode(&(bTail->getnext()),&start);
it shows error as :lvalue required as unary '&' operand
Of course it does. getnext
returns a temporary value (a copy of the pointer) and temporaries are rvalues. Rvalues don't have an associated memory address, so you may not use them as an oprand for &
.
MoveNode(&(bTail->next),&start);
It shows no error.
Well, bTail->next
is an lvalue, so there is no syntax error there.
If you need to pass into MoveNode
a pointer to a pointer, then that pointed to pointer must be stored somewhere. Since it's stored as a member in the node
, you could return a reference instead of a copy of the pointer in which case you'd be returning an lvalue and your syntax would be correct.
Upvotes: 1
Reputation: 65720
MoveNode(&(bTail->getnext()),&start);
This doesn't work because you are trying to take the address of a temporary pointer returned by getnext
. The fact that pointers can be temporary might sound strange at first, but essentially you aren't getting a pointer to where the node stores its next
pointer, but to some meaningless memory location.
If you want really want &(bTail->getnext())
to return the address of next
within that node, make getnext
return a reference to that pointer:
node *& getnext();
Upvotes: 0
Reputation: 9997
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.
Upvotes: 2