In book named “Using C++” by Rob McGregor there is following example of using pointer-to-member operator
class mycls
{
public:
int member;
int *ptr;
};
void main()
{
mycls MyClass;
// Derive a pointer type to the non-pointer class member
int mycls::*member = &mycls::member;
MyClass.ptr = new int;
mycls* pMyClass = &MyClass;
pMyClass->*member = 5;
*MyClass.ptr = 10;
cout << "pMyClass->*member = " << pMyClass->*member << "\n"; // pMyClass->*member = 5
cout << "MyClass.*member = " << MyClass.*member << "\n"; // MyClass.*member = 5
cout << "*MyClass.ptr = " << *MyClass.ptr << "\n"; // *MyClass.ptr = 10
cout << "*pMyClass->ptr = " << *pMyClass->ptr << "\n"; // *pMyClass->ptr = 10
delete MyClass.ptr;
}
In this example I don’t understand why member variable mycls::member becomes maybe a pointer after (guessing) this line of code:
int mycls::*member = &mycls::member;
What this does?
Suppose you had a local variable:
You could make a pointer to it with:
To get the pointer to member syntax, we just append
mycls::in the appropriate places:It might be clearer with an example that shows how the pointer can switch between any members of the class that are of the correct type:
Note how we create the pointer to the member
abefore we’ve created an object of typeC. It’s only a pointer to a member, not a pointer to the member of a specific object. In the ‘store’ steps, we have to say which object as well as which member.Update
In the comments the OP asked if this is the same:
No, it’s not. That is a pointer to any
int, anywhere in memory.The easiest way to understand this is to think of what it means technically. A “pointer” is an absolute location in memory: where to find an object. A “pointer-to-member” is a relative location, sometimes called an offset: where to find an object within the storage of an outer object. Internally they are just numbers. A pointer-to-member has to be added to an ordinary pointer to make another pointer.
So if you have a pointer to an object (an
intis an object!), you can use it to change what is stored at that absolute location in memory:But if you have a pointer-to-member, it is not a memory location. It is an offset, an amount to be added to a memory location. You cannot use it by itself. You must “add” it to an object pointer:
This means: go to the location in memory
ptrToObj, then move along by the distanceptrToMember.