Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining & and * operators

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.

like image 766
user1769106 Avatar asked Oct 23 '12 17:10

user1769106


3 Answers

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 n.next - and, in this case, it would remain un-initialized compile because getNext 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.

like image 82
Luchian Grigore Avatar answered Oct 29 '22 21:10

Luchian Grigore


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.

like image 24
Ed S. Avatar answered Oct 29 '22 23:10

Ed S.


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;
}
like image 21
mfontanini Avatar answered Oct 29 '22 22:10

mfontanini