Section 5.6. The Arrow Operator


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:

      item1.same_isbn(item2); // run the same_isbn member of item1 

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:

      Sales_item *sp = &item1;      (*sp).same_isbn(item2); // run same_isbn on object to which sp points 

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:

      // run the same_isbn member of sp then dereference the result!      *sp.same_isbn(item2); // error: sp has no member named same_isbn 

This expression attempts to fetch the same_isbn member of the object sp. It is equivalent to

      *(sp.same_isbn(item2));  // equivalent to *sp.same_isbn(item2); 

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:

      (*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 

More concretely, we can rewrite the call to same_isbn as

      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(); 




C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net