Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Pointers to Class Member Summary based on *C++ Primer, 5th ed.* Section 19.4: Pointers to Class Member, paired with modern C++ `std::invoke` and C++20 Ranges projections. ## 1. Ordinary Pointers vs. Pointers to Class Member (`.*`, `->*`) While an ordinary pointer `TYPE*` stores the **actual memory address of a specific live object**, a **pointer to member `TYPE CLASS::*`** stores no object address at all — it identifies **which non-`static` member within `CLASS` to select**, such as its relative byte offset inside `CLASS`. | Aspect | Ordinary Pointer `TYPE*` | Pointer to Member `TYPE CLASS::*` | | :--- | :--- | :--- | | **Target** | Actual address of a specific object in memory | Relative member slot within `CLASS`, independent of any instance | | **Initialization** | `&CLASS_INSTANCE.MEMBER` | `&CLASS::MEMBER` | | **Standalone Dereference** | ✅ `*PTR` | ❌ Must bind to an object or pointer — `CLASS_INSTANCE.*MEMBER_PTR`, `CLASS_PTR->*MEMBER_PTR` | | **`static` Members** | ✅ `static` members belong to no instance, so use `TYPE*` | ❌ Non-`static` members only | - **Overloadability:** `.` and `.*` operate directly on objects and cannot be overloaded in C++, whereas their pointer counterparts `->` and `->*` can be overloaded for smart pointers and iterators — see [Overloaded Operations]({{< relref "/programming/cpp/primer/operator-overloading.md#1-operator-overloading-fundamentals--member-vs-nonmember-guidelines" >}}). --- ## 2. Syntax for Data Members and Member Functions ### 1. Pointers to Data Members Prepend `CLASS::` before `*` to specify the class type, or use `auto` when initializing directly: ```cpp struct Point { int x; int y; }; // Equivalent to: int Point::* mp = &Point::x; auto mp = &Point::x; Point p1{1, 2}; Point* ptr = &p1; int a = p1.*mp; // Use .* on an object -> p1.x (1) int b = ptr->*mp; // Use ->* on a pointer -> ptr->x (1) mp = &Point::y; // Retarget to member y int c = p1.*mp; // p1.y (2) ``` ### 2. Pointers to Member Functions & Precedence Rule A pointer to member function must match the parameter types and qualifiers (`const`, `noexcept`) of the target function. Because the call operator `()` has higher precedence than `.*` and `->*`, **you must parenthesize `(CLASS_INSTANCE.*FUNC_PTR)(ARGS...)` and `(CLASS_PTR->*FUNC_PTR)(ARGS...)`:** ```cpp class Screen { public: char get() const { return 'A'; } char get(int r, int c) const { return 'B'; } }; // Explicit type selects the two-parameter overload, including const char (Screen::*fp)(int, int) const = &Screen::get; Screen s; Screen* sp = &s; // char c = s.*fp(0, 0); // ❌ Compile error: parsed as s.*(fp(0, 0))! char c1 = (s.*fp)(0, 0); // ✅ Bind to object first, then invoke char c2 = (sp->*fp)(0, 0); // ✅ Bind to pointer first, then invoke ``` --- ## 3. When Are They Used? You rarely type `.*` or `->*` directly in application code, but **passing `&CLASS::MEMBER` to standard library utilities is very common** — the library performs the underlying `.*` / `->*` dereference via `std::invoke`. ### 1. C++17 `std::invoke` and `std::mem_fn` - **`std::invoke` (``):** Calls ordinary functions, lambdas, data member pointers, and member function pointers through `std::invoke(CALLABLE, ARGS...)`, **inspecting `CALLABLE` at compile time to split `ARGS...` differently**: - For an ordinary function or lambda (no `this` instance), all of `ARGS...` are forwarded directly as function arguments. - For a non-`static` member pointer, **the first argument in `ARGS...` (`obj`) is consumed as the target object (`this`)**, and **any remaining arguments are forwarded as the member function's parameters**. `std::invoke` also automatically handles values/references, raw/smart pointers, and `std::reference_wrapper`: | `CALLABLE` Kind | `std::invoke` Form | How `ARGS...` Is Split & Evaluated | | :--- | :--- | :--- | | **Function / Lambda / Functor** | `std::invoke(fn, a, b)` | All args are parameters → `fn(a, b)` | | **Member Function Pointer** (`&C::Method`) | `std::invoke(&C::Method, obj, a, b)` | **1st arg `obj` = target instance (`this`)**, rest `a, b` = parameters:
• Object/ref: `(obj.*(&C::Method))(a, b)`
• Pointer / smart pointer: `((*obj).*(&C::Method))(a, b)`
• `std::ref(x)`: `(obj.get().*(&C::Method))(a, b)` | | **Data Member Pointer** (`&C::field`) | `std::invoke(&C::field, obj)` | **Only 1 target arg `obj` allowed** (returns member reference):
• Object/ref: `obj.*(&C::field)`
• Pointer / smart pointer: `(*obj).*(&C::field)` | This lets generic library templates (`std::ranges`, `std::thread`, `std::apply`) accept lambdas, member functions, and struct fields interchangeably with a single `std::invoke` call instead of writing separate overloads. - **`std::mem_fn` (``):** A raw member pointer has no `operator()`, so C++11 `` utilities cannot call it directly. Wrapping it with `std::mem_fn(&CLASS::MEMBER)` produces a callable functor whose first parameter is the target object or pointer (forwarding internally to `std::invoke`): ```cpp #include #include #include #include #include struct Box { int Scale(int factor) const { return val * factor; } int val = 10; }; Box b; auto bp = std::make_unique(Box{20}); // 1) Ordinary lambda: all of ARGS (10, 3) are function parameters int r1 = std::invoke([](int x, int y) { return x * y; }, 10, 3); // -> 30 // 2) Member function pointer: 1st arg (b, &b, bp) is the target object (this), 2nd arg (3) is Scale(factor) int r2 = std::invoke(&Box::Scale, b, 3); // (b.*(&Box::Scale))(3) -> 30 int r3 = std::invoke(&Box::Scale, &b, 3); // ((&b)->*(&Box::Scale))(3) -> 30 int r4 = std::invoke(&Box::Scale, bp, 3); // ((*bp).*(&Box::Scale))(3) -> 60 (smart pointers dereferenced too) // 3) Data member pointer: takes only the target object (b) and returns int& (extra args fail to compile) int& v = std::invoke(&Box::val, b); // b.*(&Box::val) -> 10 v = 15; // b.val == 15 std::vector words = {"hello", "", "world"}; // Wrap member function pointer into a callable functor for C++11 auto it = std::find_if(words.begin(), words.end(), std::mem_fn(&std::string::empty)); ``` ### 2. C++20 Ranges Projections (`std::ranges::sort`, etc.) The most common place you see `&CLASS::MEMBER` in modern C++. Instead of writing a verbose comparator lambda just to sort or search by one struct field, pass the member pointer as the **projection** argument: ```cpp #include #include #include struct User { std::string name; int age; }; std::vector users = {{"Alice", 30}, {"Bob", 20}}; // 2nd arg {} uses the default comparator (std::ranges::less{}, ascending); 3rd arg &User::age is the projection std::ranges::sort(users, {}, &User::age); // Equivalent lambda forms for comparison: // 1) Unary projection lambda as the 3rd argument: // std::ranges::sort(users, {}, [](const User& u) { return u.age; }); // 2) Binary comparator lambda as the 2nd argument (3rd projection omitted): // std::ranges::sort(users, [](const User& a, const User& b) { return a.age < b.age; }); ``` ### 3. `std::thread` Callbacks and Command Dispatch Tables - **Launching `std::thread` on a member function:** Pass `&Worker::Run` followed by the target object pointer `&w` and arguments. - **Command dispatch tables (*C++ Primer* 19.4 idiom):** Map enum/integer indices directly to an array of member function pointers without `if-else` chains. ```cpp #include struct Worker { void Run(int id) {} }; Worker w; std::thread t(&Worker::Run, &w, 1); // Internally executes (&w ->* &Worker::Run)(1) t.join(); // Command dispatch table example class Cursor { public: Cursor& up() { return *this; } Cursor& down() { return *this; } enum Direction { UP, DOWN }; Cursor& Move(Direction dir) { return (this->*kMenu[dir])(); // Dispatch directly by index without branching } private: using Action = Cursor& (Cursor::*)(); static constexpr Action kMenu[] = {&Cursor::up, &Cursor::down}; }; ```