Learn C++ Online

Dynamic structures (part 2)

On this page
This lesson contains approximately 33 minutes of video content.

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.

A sequence of "nodes"

Dynamic structures

Questions

Q1

QDynamic Structures, Pt 2 Q1

This question is ungraded.

The dynamic in Dynamic Structures refers to:

Q2

QDynamic Structures, Pt 2 Q2

This question is ungraded.

To access an element in a singly linked list, we must (select the best response)

Q3

QDynamic Structures, Pt 2 Q3

This question is ungraded.

A linked list with head_ and tail_ pointers is   compared to an array (whose size != capacity). Select the best answer.

Q4

QDynamic Structures, Pt 2 Q4

This question is ungraded.

What's wrong with the following code snippet? Assume that head_ is the head data member node pointer of a singly linked list object and that this snippet presents inside a member function.

while (head_ != nullptr) {
  delete head_;
  head_ = head_->next;
}
Select the best answer.

Q5

QDynamic Structures, Pt 2 Q5

This question is ungraded.

The expression head_->data is equivalent to: