How to pass a class method as an argument for another function in C++ and openGL?

user188276 picture user188276 · Mar 23, 2010 · Viewed 10.6k times · Source

I know this thing works:

void myDisplay()
{
...
}
int main()
{
...
glutDisplayFunc(myDisplay)
...
}

so I tried to include myDisplay() function to a class that I made. Because I want to overload it in the future with a different class. However, the compiler complains that

argument of type 'void (ClassBlah::)()' does not match 'void(*)()' .

Here is the what I try to make:

class ClassBlah
{
   ....
   void myDisplay()
   ....
}
......
int main()
{

    ...
    ClassBlah blah
    glutDisplayFunc(blah.myDisplay)
    ...
}

Does anybody knows how to fix this problem? Many thanks.

Answer

kibibu picture kibibu · Mar 23, 2010

Firstly, there is an implicit "this" pointer in non-static member functions, so you'll need to change your void myDisplay() in ClassBlah to be static. It's awkward to work around this limitation, which is why the C++ faq lite says don't do it

Then, you should be able to pass the functions as ClassBlah::myDisplay.

Depending on your motivation for overloading (ie are you going to hotswap implementations in and out at runtime, or only at compile time?) you might consider a utility "handler" static class that contains a pointer to your base class, and delegates responsibility through that.