CKTIS / C++
The .* operator and pointer-to-member formation
A pointer to member identifies a class member, not a particular object's member. Form it with &T::member, then apply it to an object with .* or to an object pointer with ->*.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
M T::* pm = &T::member;
R (T::* pf)(Args...) const = &T::function;
object.*pm
(object.*pf)(args...)
pointer->*pm
(pointer->*pf)(args...)A pointer to member is a distinct type, not an ordinary address inside an object. The declaration int Counter::* data declares data as a pointer to an int field of Counter, but does not by itself select a field. In the example, the initializer &Counter::value supplies the pointer value that designates value without selecting a particular object. Likewise, int (Counter::* method)(int) const declares a pointer to an implicit-object member function, and the initializer &Counter::add designates add.
Formation: &T::member. Use an explicit & and a qualified name without enclosing parentheses: &Counter::value or &Counter::add. Writing &(Counter::value) does not form a pointer to member. The built-in address-of operator yields an ordinary pointer, not a pointer to member, when applied to a static member or an explicit-object member function. If member is a static data member of class type, &T::member can call an overloaded operator&, which can return a non-pointer value or even a pointer-to-member value.
Application: object.*pm. The .* operator combines an object with the designated member. For a field on an lvalue object, the result is an lvalue, so c.*data = 10 changes c.value if const qualification permits it. Call a function as (c.*method)(5); the parentheses are needed because of operator precedence. For an object pointer, use pointer->*pm, equivalent to (*pointer).*pm.
The object must have the appropriate class type or a derived type with an unambiguous, accessible base class. Applying a null pointer to member causes undefined behavior. The example targets C++23; the supplied working draft is a moving document, not a frozen C++23 edition.
Examples
#include <iostream>
struct Counter {
int value;
int add(int n) const { return value + n; }
};
int main() {
Counter c{7};
int Counter::* data = &Counter::value;
int (Counter::* method)(int) const = &Counter::add;
c.*data = 10;
std::cout << c.*data << '\n';
std::cout << (c.*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.