This is one of the two "pointer-to-member" operators in C++.(NOT available in C) (the other is .*) It is rarely used, but can be very useful for that old practice lost from C: callbacks!

Say you have this class:

class RabidFoo {
   int a,b,c;
Now say you want to write a value to a, b, and c in separate places. The standard method is to write three different functions:
void WriteToA(RabidFoo *rf,int value) { rf->a=value; }
void WriteToB(RabidFoo *rf,int value) { rf->b=value; }
void WriteToC(RabidFoo *rf,int value) { rf->c=value; }
But then what happens when want to have a function that say adds two numbers together and stores it to one of these variables? You have to write three more, and three more for the next task and so on. Then imagine you add a fourth variable, d to this class. You have to write new functions at every level to accomodate it!

This is where the ->* operator comes in. (surprise, surprise) You write one function that takes a pointer to a member variable:

void WriteTo(RabidFoo *rf,int RabidFoo::*var,int value) {
   rf->*var = value;
(Notice that the * has a scope now.) Then you can write one function at every level, and no worries if you add int d sometime later.

Oh yes, here's how you'd call that:

   RabidFoo n;
   WriteTo( &n, &RabidFoo::a, 7);

The real power comes when you apply this to member functions. It's not terribly much more difficult than this.

class RabidFoo {
   bool a(int);
   bool b(int);
   bool c(int);

bool (RabidFoo::*pFunc)(int);
pFunc = &RabidFoo::a;

RabidFoo n,*p=&n;


Log in or register to write something here or to contact authors.