Sign in to follow this  
Omelas0469

How to register display callback function as a member function

Recommended Posts

Hi guys, I've been working on a pacman man clone for awhile now. I'm using C++ and the GLUT library. Until now I've been using global variables in my driver code which are pointers to pacman and the 4 ghosts. In main I register my display callback as follows: glutDisplayFunc(displayScene()); and displayScene was found in the same file as main():
void displayScene()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glPushMatrix();
	Map::drawMap();
	pacman->draw();
	blinky->draw();
	glPopMatrix();
	glFlush();
}
but now because I don't want to use global variables anymore, I decided to introduce a new class called Game which has pointers to the characters as its attributes and I moved displayScene to class Game. Now, in my main() I have
	Game game;
	glutDisplayFunc(game.displayScene());
but I get an error: error C2664: 'glutDisplayFunc' : cannot convert parameter 1 from 'void' to 'void (__cdecl *)(void)' 1> Expressions of type void cannot be converted to other types How can I resolve this?

Share this post


Link to post
Share on other sites
You can't basically.

Reason? A pointer to a function is a straight memory pointer. Pointer to a member is (underneath) a memory pointer for the instance plus the vtable offset of the function to call. So they're basically incompatible -- they take different amounts of memory to store apart from anything else.

The sensible way to do this is to use a "thunk" class which has static member functions. You set up all the GLUT callbacks to those static member functions.

It can then keep a member pointer for each one and call the appropriate function out.

If you use a decent member pointer encapsulating template class (eg, the one in Boost), your "thunk" class doesn't need to know what interface type it's calling into which will nicely decouple your code.


One of the things I've done in an application is have "stacks" of handlers managed inside the singleton thunk object.

So when you open (say) a UI window over the display, that becomes the "first responder" to keypress events. It also paints in response to the paint events, but they also continue down the stack and cause the "world" renderer behind the window to paint.

This way you can stack up windows properly and pop them off when you're done without having to worry about restoring states and so on.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this