5.6. The Arrow Operator
The arrow operator (->) provides a synonym for expressions involving the dot and dereference operators. The dot operator (Section 1.5.2, p. 25) fetches an element from an object of class type:
If we had a pointer (or iterator) to a Sales_item, we would have to dereference the pointer (or iterator) before applying the dot operator:
item1.same_isbn(item2); // run the same_isbn member of item1
Here we dereference sp to get the underlying Sales_item. Then we use the dot operator to run same_isbn on that object. We must parenthesize the dereference because dereference has a lower precedence than dot. If we omit the parentheses, this code means something quite different:
Sales_item *sp = &item1;
(*sp).same_isbn(item2); // run same_isbn on object to which sp points
This expression attempts to fetch the same_isbn member of the object sp. It is equivalent to
// run the same_isbn member of sp then dereference the result!
*sp.same_isbn(item2); // error: sp has no member named same_isbn
However, sp is a pointer, which has no members; this code will not compile.Because it is easy to forget the parentheses and because this kind of code is a common usage, the language defines the arrow operator as a synonym for a dereference followed by the dot operator. Given a pointer (or iterator) to an object of class type, the following expressions are equivalent:
*(sp.same_isbn(item2)); // equivalent to *sp.same_isbn(item2);
More concretely, we can rewrite the call to same_isbn as
(*p).foo; // dereference p to get an object and fetch its member named foo
p->foo; // equivalent way to fetch the foo from the object to which p points
sp->same_isbn(item2); // equivalent to (*sp).same_isbn(item2)
Exercises Section 5.6
Exercise 5.18:Write a program that defines a vector of pointers to strings. Read the vector, printing each string and its corresponding size.Exercise 5.19:Assuming that iter is a vector<string>::iterator, indicate which, if any, of the following expressions is legal. Explain the behavior of the legal expressions.
(a) *iter++; (b) (*iter)++;
(c) *iter.empty() (d) iter->empty();
(e) ++*iter; (f) iter++->empty();