Take this code:
struct mystruct
{
int var;
mystruct() : var(0) {}
};
int main()
{
mystruct ins;
int* p = &ins.var;
*p = 1;
}
So what are some concrete really good examples of uses for the class member pointer?
int X::*p = &X::data; /* p contains offset */
X object;
X *objptr = new X;
int i = object.*p;
int j = objptr->*p;
It seems the your question is about pointers of pointer-to-data-member type. In C++ there are also pointers of pointer-to-member-function type. The two have something in common at some abstract level, but otherwise they are different.
Pointer of pointer-to-data-member type is applicable to any instance of the class. An ordinary pointer always points to a member of a specific instance of the class. Pointer of pointer-to-data-member type is a higher level implementation of the idea of “run-time offset” from the beginning of a class object. It is a relative pointer. In that way it is completely different thing from ordinary pointers, which are absolute pointers.
To illustrate that with an example, let’s say you have an array of classes with three members of the same type
x,yandzand you need to set all members with the same name to
0in the entire array, without changing any other members. Here’s how you can do it using a pointer of pointer-to-data-member typeNow, by using this function you can do
to set all
xs to zero. Or you can doto set all
ys to zero. You do can all this with a single function, and what’s also important, the member selection is performed by a run-time parameter (as opposed to a compile-time one).You cannot do something like this with ordinary pointers. In fact, you can’t do it in any other way.