Tom Martin
Tom Martin

Reputation: 300

Error when sending function as argument, sometimes

The error is 'GLHandler::handleKeys': non-standard syntax; use '&' to create a pointer to member four times, on different functions.

I am trying to make a wrapper class for initialising glut, to make things cleaner.

The error appears on 4 lines all for the same reason, though I'm not sure why.

All of these are setting callbacks

Inside initGlut function:

glutKeyboardFunc(this->handleKeys); 
glutDisplayFunc(this->render);
glutTimerFunc(1000 / SCREEN_FPS, this->runMainLoop, 0);

Inside runMainLoop function

glutTimerFunc(1000 / this->SCREEN_FPS, this->runMainLoop, val);

The errors being thrown here do not exist when called identically from inside main which leads me to believe something is wrong with the class, but I can't see it.

Upvotes: 2

Views: 120

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

this->handleKeys, this->render and this->runMainLoop are class methods rather than functions. The callback has to be a function or a static method.

e.g. See glutDisplayFunc (and see also freeglut Application Programming Interface):

glutDisplayFunc sets the display callback for the current window.

Usage

void glutDisplayFunc(void (*func)(void));

Note, the method of a class can only be called by an object of the class. The pointer to an method is not sufficient. You can imagine the method of a class, as a function where the first parameter is the pointer to an object of the class.

If there is a class

class Foo
{
public:
    void render(void);
};

Then a pointer to the method render can be get by &Foo::render. But the type of the pointer is void(Foo::*)(void) rather than void(*)(void)

Upvotes: 2

Related Questions