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.