I've been reading through an implementation of a List (and its node) using classes and I've found a couple things I don't quite understand. Here's the code in the Node class that I don't understand:
class Node {
private:
Data data;
Node* next;
public:
Node*& getNext();
};
Node*& Node::getNext()
{
return this->next;
}
What is *& exactly? I don't get what kind of variable is returned by that method.
I think I get it now, later on I have these lines (inside class List):
Node** node = &first;
node = &(*node)->getNext();
Does that mean I'm storing next's address in node*?
Note: Second question was answered in the comments. Thanks for replies.
That's a reference to a pointer. It means that the Node*
the function returns is an alias for Node::next
.
For example, say you have:
Node n;
n.getNext() = NULL;
this sets n.next
to NULL
.
If the method didn't return by reference
Node* Node::getNext() //no reference
{
return this->next;
}
the same code
Node n;
n.getNext() = NULL;
wouldn't modify compile because n.next
- and, in this case, it would remain un-initializedgetNext
returns an rvalue
here.
Alternatively, returning by reference:
Node*& x = n.getNext();
x = new Node;
would modify n.next
, as x
is a reference to n.next
.
Node*& getNext();
Returns a reference to a Node*
. Why they chose to return a non-const reference to a pointer, which allows for its value to be changed by callers of the function... I don't know.
That means you're returning a pointer by reference. Meaning someone can modify the actual pointer inside a node:
Node anode = /* something... */;
anode.getNext() = nullptr;
assert(anode.getNext() == nullptr); // assertion passed!
This doesn't look like a situation in which you would use this. Just return the pointer:
Node* Node::getNext()
{
return next;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With