CKTIS / C++
Operator ->*: member access through an object pointer
The built-in ->* operator combines an object pointer with a pointer to a class member. It lets you read or modify a data member, or call a member function selected by that member pointer.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
object_ptr->*data_member_ptr
(object_ptr->*member_function_ptr)(arguments)The built-in ->* applies a member pointer to the object addressed by its left operand: ptr->*pm is equivalent to (*ptr).*pm. The left operand points to an object of class T, or a class with T as an unambiguous, accessible base; the right operand is a pointer to a member of T.
ptr->value selects a member named in the code, whereas ptr->*data uses a member-pointer value. The .* operator takes the object itself rather than a pointer to it. For a data member, ->* yields an lvalue; whether it is writable depends on factors including const.
Call a member function as (ptr->*method)(5). Parentheses are necessary because function call () has higher precedence than ->*. A result designating a member function can only be used to call that function.
Outside construction and destruction, the object pointer must point to a suitable object within its lifetime. During construction and destruction, member access follows the special rules in [class.cdtor]. For example, in the constructor body, this->*data can access an already initialized data member before the enclosing object's lifetime formally begins. Violating the rules for accessing the object can cause undefined behavior. If the right operand has a pointer-to-member type but its value is null, evaluating the ->* expression causes undefined behavior. In contrast, ptr->*nullptr is ill-formed: the literal nullptr has type std::nullptr_t, not a pointer-to-member type. This description concerns the built-in operator. The source is an evolving working draft, not a frozen C++23 publication.
Examples
#include <iostream>
struct Counter {
int value;
int add(int amount) const { return value + amount; }
};
int main() {
Counter counter{7};
Counter* ptr = &counter;
int Counter::* data = &Counter::value;
int (Counter::* method)(int) const = &Counter::add;
ptr->*data = 10;
std::cout << (ptr->*data) << '\n';
std::cout << (ptr->*method)(5) << '\n';
}
Result
10 15
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.