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 ):
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 . 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()
. 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!
So the final correct version of our simple program using the pointer member access operator would look like:
Checkpoint 18.8.2.
You have attempted of activities on this page.