Quick Q: Pointer to class data member “::*”

Quick A: a pointer that lets you access the value of the member of an instance.

Recently on SO:

Pointer to class data member “::*”

It's a "pointer to member" - the following code illustrates its use:

#include <iostream>
using namespace std;

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;

    Car c1;
    c1.speed = 1;       // direct access
    cout << "speed is " << c1.speed << endl;
    c1.*pSpeed = 2;     // access via pointer to member
    cout << "speed is " << c1.speed << endl;
    return 0;
}

As to why you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.

Edit: I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:

void Apply( SomeClass * c, void (SomeClass::*func)() ) {
    // do hefty pre-call processing
    (c->*func)();  // call user specified function
    // do hefty post-call processing
}

The parentheses around c->*func are necessary because the ->* operator has lower precedence than the function call operator.

Add a Comment

Comments are closed.

Comments (1)

0 0

leetNightshade said on Mar 13, 2019 02:21 PM:

Pointer to member function or data is useful in a run-time reflection system. When you want to be able to run/poke code that you haven't compiled against to know already what it contains.

Let's say executable and an arbitrary DLL share a reflection system. The DDL can register all of it's data and available functions to the reflection system, and the executable can access and process data using those registrations (the member pointer functions and data). Needed for run-time reflection.