A lot of C++ books and tutorials explain how to do this, but I haven\'t seen one that gives a convincing reason to choose to do this.
I understand very well why functio
I used a function pointer to a member function in a scenario where I had to provide a function pointer to a callback with a predefined parameter list (so I couldn't pass arbitrary parameters) to some 3rd-party API object.
I could not implement the callback in the global namespace because it was supposed to handle incoming events based on state of the object which made use of the 3rd party API which had triggered the callback.
So I wanted the implementation of the callback to be part of the class which made use of the 3rd-party object. What I did is, I declared a public and static member function in the class I wanted to implement the callback in and passed a pointer to it to the API object (the static
keyword sparing me the this
pointer trouble).
The this
pointer of my object would then be passed as part of the Refcon for the callback (which luckily contained a general purpose void*
).
The implementation of the dummy then used the passed pointer to invoke the actual, and private, implementation of the callback contained in the class = ).
It looked something like this:
public:
void SomeClass::DummyCallback( void* pRefCon ) [ static ]
{
reinterpret_cast(pRefCon)->Callback();
}
private:
void class SomeClass::Callback() [ static ]
{
// some code ...
}