Fog Creek Software
Discussion Board

How is the ->* operator used?

The previous posters name got me thinking... Maybe someone can tell me how the ->* is used?  I've seen in textbooks but never in RL.

Tuesday, August 3, 2004

It's used as described in textbooks, to implement pointer-to-member in C++ ... for example (from the first Google hit)

Christopher Wells
Tuesday, August 3, 2004

a->b is the same as (*a).b
a->*b is the same as (*a).(*b)

But it´s always possible to avoid writing like this

Tuesday, August 3, 2004

Coder - that isn't correct. ->* is a distinct operator all by itself, it isn't just a -> and a *.

BJ - it isn't commonly used. The one time that I've found it useful is for certain types of callback mechanisms where you want to have some other code call back into a member function of a particular class, like when an event is fired.

The thing that is firing the event needs to have a pointer to the class whose member function will be called, and a pointer to the member function that it wants to call - then it can call the member function by using ->*, like  class_instance->*member_function.

It allows for some flexibility in setting up events between classes. I use it in some helper classes that make it easier for events like Win32 timers (that don't carry any state data) to call back into class methods where the class's state is easily available.

Tuesday, August 3, 2004

I've used it only once (and then rewrote the code because it was weird), but I think it goes like this:

struct Foo
    int i, j;

void bar()
    bool cond = /**/;
    int Foo::*pFooInt = cond ? &Foo::i : &Foo::j;
    Foo* pFoo = /**/;
    pFoo->*pFooInt = 2;

The pointer-to-member allows you to bind a pointer to a member variable (as the name implies).  You rarely need it, but when you need it, you really need it.  Most often used with a function pointer and a finite-state machine.  The idea is the same, but the syntax is dirtier (it's the declaration that ugly).  You can then call the member function through the pointer.

Wednesday, August 4, 2004

I should clarify: pointer to member variable is what I rewrote the one time I wrote it.  Pointer to member function is slightly less unusual, and is a common way of implementing some finite state machines.

Wednesday, August 4, 2004

*  Recent Topics

*  Fog Creek Home