Function pointers

I am trying to use a function pointer to allow a function to hook events in a class.

The callbacks look like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
typedef bool(* SfuiEventCallback)(class sfui*, sf::Event);
...
class sfui {
	...
	public:
		/** Function to call (if any) when the window is closed */
		SfuiEventCallback	OnClosed;
		/** Function to call (if any) when the window is resized */
		SfuiEventCallback	OnResized;
		/** Function to call (if any) when window focus is lost */
		SfuiEventCallback	OnLostFocus;
		/** Function to call (if any) when window focus is gained */
		SfuiEventCallback	OnGainedFocus;
		/** Function to call (if any) when a key is pressed */
		SfuiEventCallback	OnKeyPressed;
		/** Function to call (if any) when a key is released */
		SfuiEventCallback	OnKeyReleased;
		/** Function to call (if any) when the mouse moves */
		SfuiEventCallback	OnMouseWheelMoved;
		/** Function to call (if any) when a mouse button is pressed */
		SfuiEventCallback	OnMouseButtonPressed;
		/** Function to call (if any) when a mouse button is released */
		SfuiEventCallback	OnMouseButtonReleased;
		/** Function to call (if any) when the mouse moves */
		SfuiEventCallback	OnMouseMoved;
	...
};


And I use it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool handle_keypress(sfui* sfui_obj, sf::Event event)
{
	return true;
}

int main()
{
	sfui gui(sf::VideoMode(640, 480), "sfui");
	gui.OpenWindow();
	gui.LoadFont("FreeMono.ttf", 32.f);
	gui.OnKeyPressed = handle_keypress;

	while (gui.IsOpen()) {
		gui.HandleEvents();
		gui.RedrawWindow();
		gui.UpdateWindow();
	}

	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
bool sfui::DispatchEvent(void)
{
	switch (this->event.Type) {
		...
		case sf::Event::KeyPressed:
			if (this->OnKeyPressed != NULL)
				return (*(this->OnKeyPressed))(this, this->event);
			else
				return this->Default_OnKeyPressed();
		...
	}
	return false;
}


But when a key is pressed, there is a segmentation fault (unless I leave sfui::OnKeyPressed as NULL).

Basically what I'm trying to do is have a pointer to a function that can be used to set handlers for events. The idea is that there is a default action and a user-defined action. The user can set a handler for each event or leave the pointers set to NULL (as they are in the constructors), in which case the default action is taken (usually just return true;). If the user doesn't want the handler to be called any more they should be able to set the function pointer to NULL and the default action will be performed next time the event occurs. What is the proper way to do this?
Last edited on
Shouldn't line 7 (in DispatchEvent()) be:

return this->OnKeyPressed(this, this->event);

?
Last edited on
Yes, you're right, that fixed it.
Thanks filipe!
Topic archived. No new replies allowed.