Dynamic structures (part 2)
The arrow operator
Before we begin, I would like to introduce to you the "arrow" operator, ->
. What is this operator
and why is it made available to us?
Since postfix operators bind tighter than prefix operators in C++, given where n1
is a Node
pointer, and a Node
object has the member Node* next
, a pointer to another Node
object,
n1.next
This is problematic since we're attempting to access n1
's next
, but n1
is a pointer to a node, not a Node
object. We need to dereference n1 to get the node object it points to.
However, if we attempt to write,
*n1.next
We have the same problem since the postfix operator is applied first, and a pointer doesn't have next
(it's the object pointed to that does, but the prefix *
is applied after postfix .
). To get the right order of operations on the object, we would need to write
(*n1).next
This ensures that the dereference operation occurs first; that next
is invoked on the Node object, not the Node pointer, as problematic in the previous examples.
Accessing a member of an object pointed to is a common operation, but it is not fun to type out (*n1).next
. So, there's the arrow operator (member access operator), which combines the dereference and dot access, similar to how subscripting combines pointer arithmetic and dereference.
n1->next // first dereference the pointer n1 to get the Node object pointed to, then invokes next on that Node object.