CKTIS / C++
Pointer-to-member declarations: `int C::*` and `const` member functions
Declare a pointer to a non-static `int` data member and a pointer to a `const` member function. See how the declared type selects an overload and how to use either pointer with an object.
Version: ISO C++23; implementation support may vary
Syntax
int C::* data = &C::value;
R (C::* method)(Args...) const = &C::f;
using DataMember = int C::*;
using ConstMemberFunction = R (C::*)(Args...) const;
// C is the class, R is the return type, and Args... is a template type-pack expansion.
// Concrete declaration of a pointer to an int(int) const member function:
int (C::* call)(int) const = &C::f;int C::* data = &C::value; declares a pointer to a non-static int data member of C. The C:: names the class scope, and &C::value designates the member without taking the address of a particular object's field. In contrast, &obj.value has type int* when obj is neither const nor volatile and value is an ordinary int field.
R (C::* method)(Args...) const declares a pointer to a non-static member function with an implicit object parameter. R is the return type, and Args... expands a pack of parameter types. The parentheses group C::* method. The trailing const qualifies the function, not the pointer: it lets you call the function on a const object. In int (C::* method)(int) const = &C::f;, the target type selects the const overload rather than the non-const one.
To form a pointer to member, write &C::value or &C::f, without parentheses around the qualified name. Taking the address of a static member gives an ordinary object or function pointer. In C++23, taking the address of a member function with an explicit object parameter (this at the start of the parameter list) also gives an ordinary function pointer.
Use obj.*data with an object or ptr->*data with a pointer to an object. Keep the parentheses when calling: (obj.*method)(2) or (ptr->*method)(2). A pointer to member is not bound to a particular object and does not extend its lifetime. Apply it to a suitable live object; applying a null member pointer (nullptr) has undefined behavior.
Examples
#include <iostream>
struct C {
int value;
int f(int n) { return value - n; }
int f(int n) const { return value + n; }
};
int main() {
int C::* data = &C::value;
int (C::* method)(int) const = &C::f;
C obj{10};
obj.*data = 40;
const C* ptr = &obj;
std::cout << (obj.*data) << '\n';
std::cout << (ptr->*method)(2) << '\n';
}Result
40 42
`obj.*data` stores `40`. The call through `ptr` invokes the selected `const` overload, which adds `2`, so the program prints `40` and then `42`.
Related lessons
- C++ · Lesson 54 · Intermediate · Version: 2