C++ allows you to generate a special type of pointer that “points” generically to a member of a class, not to a specific instance of that member in an object. This sort of pointer is called a pointer to a member, or pointer-to- member, for short. A pointer to a member is not the same as a normal C++ pointer. Instead, a pointer to a member provides only an offset into an object of the member's class at which that member can be found. Since member pointers are not true pointers, the . and –> operators cannot be applied to them. To access a member of a class given a pointer to it, you must use the special pointer-to-member operators .* and –>*. They allow you to access a member of a class given a pointer to that member.
When you are accessing a member of an object given an object or a reference to an object, use the .* operator. When accessing a member given a pointer to an object, use the –>* operator.
A pointer to a member is declared by using the general form shown here:
type class-name::*ptr;
Here, type is the base type of the member, class-name is the name of the class, and ptr is the name of the pointer-to-member variable being created. Once created, ptr can point to any member of its class that is of type type.
Here is a short example that demonstrates the .* operator. Pay special attention to the way the member pointers are declared.
#include <iostream>
using namespace std;
class cl {
public:
cl(int i) { val=i; }
int val;
int double_val() { return val+val; }
};
int main()
{
int cl::*data; // int data member pointer
int (cl::*func)(); // func member pointer
cl ob1(1), ob2(2); // create objects
data = &cl::val; // get offset of val
func = &cl::double_val; // get offset
cout << "Here are values: ";
cout << ob1.*data << " " << ob2.*data << "\n";
cout << "Here they are doubled: ";
cout << (ob1.*func)() << " ";
cout << (ob2.*func)() << "\n";
return 0;
}
The pointer-to-member operators are not supported by C.