Skip to main content

Section 18.8 Object Member Access with Pointers

When using pointers with objects, we are likely to encounter a syntax annoyance. Say we have a Pointer called myPointer that points at a Point object and we want to call the getX() function of that Point. We know that the pointer is just a memory address. To use it we need to dereference it - *myPointer will give us “the object that myPointer points at”. So we write the following to access the getX() of that object (using our Point.cxx ):
Listing 18.8.1.
The compiler spits out an error message that looks something like this:
request for member ‘getX’ in ‘myPointer’, which is of pointer type ‘Point*’ (maybe you meant to use ‘->’ ?)
The issue is one of precedence
 1 
. We intended to say, “first dereference the pointer, then use the getX member of that object”. However, . is interpreted before *. So what we said was “use the getX member of the pointer (.), then dereference the result (*).”. It is as if we had written *(myPointer.getX()), which does not make sense because myPointer is just a memory address, not an object, and thus has no getX().

Insight 18.8.1.

A pointer is just a memory address, not an object. We can’t use it like an object.
One way to fix this is to use parentheses to make the order of operations clear:
(*myPointer).getX();
That will work as intended (you can try it in the program above). However, it is a bit clunky. And it can get really clunky if we have a series of pointers to dereference. Something like the statement below is quite hard to quickly read and comprehend:
(*(*(*cylinderPointer).getBasePointer()).getCenterPointer()).getX();
C++ provides a shorthand for this situation. Instead of using * and . together, we can use the pointer member access operator -> (also sometimes called the arrow operator. This operator is used to access members of an object through a pointer. You can think of myPointer->getX() as saying “go to the thing myPointer points at and then use the getX() member of that object”. No parentheses needed!
p points to an object. We can use -> to start from p and access the object’s member
Figure 18.8.2. The -> operator follows a pointer to access the thing it points to and then uses the member of that object.
So the final correct version of our simple program using the pointer member access operator would look like:
Listing 18.8.3.

Checkpoint 18.8.1.

Checkpoint 18.8.2.

Which is the best way to pronounce p->foo()?
  • “go to the thing p points and use the foo method of it”
  • “use the foo method of p”
  • “go to the thing that p’s foo method points at”
You have attempted of activities on this page.