CKTIS / C++
Operator ->: member access through a pointer
The -> operator accesses a data member or calls a member function of the object a pointer points to. For the built-in operator, pointer->member is equivalent to (*pointer).member.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
pointer->member
pointer->member_function(arguments)
(*pointer).memberThe built-in -> operator combines pointer indirection with member access. Writing pointer->member means (*pointer).member. Use object.member for an object or a reference to it, and pointer->member for a pointer. The parentheses in (*pointer).member are necessary because . binds more tightly than unary *.
In the example, pointer points to counter. Calling pointer->increment() increases its value field, and both output statements print 5. The operator does not copy the pointed-to object.
Accessing a non-static member normally requires a pointer to a suitable object within its lifetime. The rules for construction and destruction also allow access to an initialized non-static data member through this in the constructor body, before the containing object's lifetime formally begins, and in the destructor body, after that object's lifetime formally ends. Access through nullptr or a dangling pointer causes undefined behavior; -> does not validate the pointer.
A class can overload operator->, for example as a smart-pointer type. The result of that call is processed with -> again until an ordinary pointer is reached. Equivalence to (*pointer).member applies to the built-in operator, not to arbitrary overloads.
Examples
#include <iostream>
struct Counter {
int value;
void increment() {
++value;
}
};
int main() {
Counter counter{4};
Counter* pointer = &counter;
pointer->increment();
std::cout << pointer->value << '\n';
std::cout << (*pointer).value << '\n';
}
Result
5 5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.