I'm trying to create some type of callback system for events. I have a function where I'm attempting to set a member to a pointer to a function but I'm receiving an error. This is what I attempted to do:

void (MyClass::*test)() = &MyClass::TestCallback;

And then in the class declaration for "MyClass" I put this:

void SetCallback(void (MyClass::*callback)());

But I'm getting this error: error: expected ')' before '::' token|

anyone have any ideas?

7 Years
Discussion Span
Last Post by mike_2000_17

Hm.. not quite. I understand how to work with pointers to normal functions. I even understand how to work with pointers to methods. The confusion arises when I try to pass the method pointer as a parameter.

edit: I found this example dealing with method pointers (but not passing them as parameters):

class Foo
                double One( long inVal );
                double Two( long inVal );

void main( int argc, char **argv )
	double (Foo::*funcPtr)( long ) = &Foo::One;

 	Foo aFoo;

 	double result =(aFoo.*funcPtr)( 2 ); 
	return 0;

So I thought making a function like..

void SetFuncPtr(void (Foo::*funcPtr)(long));

would work. However I was getting errors as posted above. I tried including a template like..

template<class Foo> void SetFuncPtr(void (Foo::*funcPtr)(long));

but still no avail. At that point I was getting another error.. no matching function for call to..

Edited by michdd: n/a


I seem to have overcome the problem by defining the interface and implementation in the same file. However I've come across another issue.. I currently do this:

template <class Client> void SetMouseClickCallback(void (Client::*callback)()) {
            MouseClickCallback = callback;

However, MouseClickCallback looks like this:

void (Client::*MouseClickCallback)();

which won't work because again, Client isn't defined. So I'm unsure as to how I can store this..


This seems unnecessary.. Shouldn't I just be able to use the Client type if I include the header file? I have included the header file that has the class interface but I still get 'Client' has not been declared|


I was able to solve this problem using forward-declaration!

Edited by michdd: n/a


I know you solved the problem, but may I suggest a more elegant method IMO. This is a typical case where an interface class and multiple inheritance could do very well:

class IMouseClickCallback {
    virtual void MouseClickCallback() = 0;

class Client : public some_other_base_if_any, public IMouseClickCallback {
    virtual void MouseClickCallback(); //with implementation in cpp

#include "Callbacks.h" //no need for forward-declarations, just include the header of the interface.

void SetMouseClickCallback(IMouseClickCallback* Obj);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.