CKTIS / C++
Pointer-to-member declarators
A pointer to member identifies a non-static data member or member function without binding to a particular object. Declare it using C::*, then apply it to an object with .* or through an object pointer with ->*.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
T C::* data = &C::member;
R (C::* function)(Args...) = &C::method;
object.*data;
pointer->*data;
(object.*function)(args...);
(pointer->*function)(args...);A pointer to member is a distinct type from an ordinary pointer. A pointer-to-data-member declarator takes the form T C::* data, while a pointer-to-member-function declarator uses R (C::* function)(Args...). The example initializes these values with &Counter::value and &Counter::add.
operator.* applies a member pointer to an object: object.*data. operator->* applies it through an object pointer: pointer->*data. Calling the function requires parentheses: (object.*function)(3) or (pointer->*function)(2).
Member pointers cannot designate static members or reference-typed data members. Use them with a valid, live object; applying a member pointer whose value is nullptr causes undefined behavior.
The example sets value to 7, then increases it by 3 and 2. The expected output is 7, 10, and 12, each on its own line.
Examples
#include <iostream>
struct Counter {
int value;
int add(int n) { return value += n; }
};
int main() {
int Counter::* data = &Counter::value;
int (Counter::* function)(int) = &Counter::add;
Counter object{4};
Counter* pointer = &object;
object.*data = 7;
std::cout << pointer->*data << '\n';
std::cout << (object.*function)(3) << '\n';
std::cout << (pointer->*function)(2) << '\n';
}
Result
7 10 12
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.