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 ):
. 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().
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:
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!