The arrow operator

Published

2023-08-05

In our introduction to C++ we saw how to use the arrow operator to access members within a class, e.g.,

this->name = name;

Now we see that this is a pointer. So what really is that arrow operator?

The arrow operator allows for member access via a pointer. It dereferences the pointer to get the object in question, then accesses the specified member. In effect, this->name is just syntactic sugar for (*this).name.

Notice that you can use this with any pointer to an object with member fields or methods. For example, where fooPtr is a pointer to an object of the Foo class, we can use

fooPtr->someMethod();

to call some Foo method, or

fooPtr->x;

to access a public member field of Foo.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

All materials copyright © 2020–2023, The University of Vermont. All rights reserved.