- Learn C++ - https://www.learncpp.com -

9.18 — Member selection with pointers and references

It is common to have either a pointer or a reference to a struct (or class). As you learned previously, you can select the member of a struct using the member selection operator (.):

This syntax also works for references:

However, with a pointer, you need to use the arrow operator:

The arrow operator does the same as an indirection followed by the . member selection operator

Note that indirection through the pointer must be enclosed in parentheses, because the member selection operator has a higher precedence than the indirection operator.

The arrow operator is not only easier to type, but is also much less prone to error because the indirection is implicitly done for you, so there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator instead of the . operator.

Rule

When using a pointer to access the value of a member, use operator-> instead of operator. (the . operator)

The member selection operator is always applied to the currently selected variable. If you have a mix of pointer- and normal member variables, you can see member selections where . and -> are mixed.


9.19 -- For-each loops [1]
Index [2]
9.17 -- References and const [3]