Using a class method as a callback function

I’m trying to use a class method in C++ to use as callback function in glutDisplayfunc but when i try to compile it shows this error:

8: error: cannot convert ‘void (Stateq::)()’ to 'void ()()’ for argument ‘1’ to ‘void glutDisplayFunc(void (*)())’

I’ve been trying to cast it without any solution. Anyone knows how to solve it?


Because methods are not same as functions. Methods require an instance to be called and therefore they can’t be used as callback function (in this case). However it should be possible to use static methods as they don’t have to be called by an instance.

edit: Or other possibility… declare a normal callback function which calls a given method of your class (on some provided instance)

Thanks… I think that you said the solution… a class with a static member that acts as callback and there a call to the member of the other class seems a good solution…

Thanks again

You can use non-static class methods as callbacks, but these callbacks must support “thiscall” calls. I believe glut doesn’t support that since it’s not object-oriented library.

Another solution is to have a struct in your class that overloads operator(), like

class A
struct Function
void operator()(int a)

This is a common workaround for passion member functions to callbacks in STL. I have not tried it with GLUT though.

There is also the possibility of using std::mem_fun_ref, which essentially binds your function to a struct automatically,

glutCallBack( std::mem_fun_ref(Class::function) );

I have not tried this with GLUT either, but again it is often used with STL.

Has this problem been solved?(the solutions that people posted here confirmed??) I am having the same problem and can’t seem to get it to work.

please help

You can use static member functions as glut callback. From this static member function you can call your other member function. For this, you have to get an object instance from somewhere (global variable, static variable, singleton pattern, …).

You can do the same with a global (non-member) function.

The solution with operator() and the one with mem_fun_ref are wrong. They only work with template libraries.