Pointers-to-members are a special gadget in C++ that tell only tell you about a which member of a class you want without pertaining to any object. You need to combine a pointer-to-member with an object instance in order to obtain an actual member, whether it be a data or a function member.
Think of pointers-to-member as “offsets”. Also, remember that pointers-to-member are not pointers!
We can rewrite your code to make it a bit clearer:
struct Foo
{
int a;
int b;
double f(int, int);
double g(int, int);
};
int main()
{
int Foo::*ptm = &Foo::a;
double (Foo::*ptmf)(int, int) = &Foo::f;
Foo x, y, z;
int numbers[] = { x.*ptm, y.*ptm, z.*ptm }; // array of Foo::a's
ptm = &Foo::b; // reseat the PTM
int more[] = { x.*ptm, y.*ptm, z.*ptm }; // array of Foo::b's
double yetmore[] = { (x.*ptmf)(1,2), (y.*ptmf)(1,2) };
ptmf = &Foo::g;
double evenmore[] = { (x.*ptmf)(1,2), (y.*ptmf)(1,2) };
}
Note how we’re using the pointers-to-member to refer only to the class member, and we can use that to get the same relative class member out of different objects.
(By contrast, we can also form a real pointer to an actual object member: int * p = &x.a;
. That’s because the member-int
is actually an integer. But we cannot do anything analogous for member functions, because member functions are not functions (e.g. you cannot call them).)
Make sure you understand the difference between classes and objects, and this should become very clear!
solved use of pointer-to-member operators? [closed]