Are function pointors right for me?

An example of what I need this for:

Imagine I have a button class that has a method called onClick(). Whenever the button is clicked the method onClick() is called. That's all fine and dandy, but there's a problem: every object will need a different method body for their own onClick() method. So my need is this: a way to assign a a new function to a default function in an existing object so I can make my buttons actually do something.

The only thing I've found to help me with this is a function pointer, so pls tell me if you know anything better. Thanks!!
Last edited on
You could also make custom button classes that override their parent's onClick method.
Consider using function objects instead of raw pointers.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <functional>
#include <iostream>
#include <array>

//We cannot touch this class
class Button
{
public:
	virtual void onClick()
	{

	}
};

void click_button(Button& button)
{
	button.onClick();
}

class CustomButton: public Button
{
	const std::function<void(void)> callback;
public:
	CustomButton(std::function<void(void)> cb) : callback(std::move(cb)) {}

	virtual void onClick() override
	{
		callback();
	}
};

void meow() {std::cout << "meow";}
void beep() {std::cout << "beep";}
void clack() {std::cout << "clack";}

int main()
{
	std::array<CustomButton, 3> buttons {{{meow}, {beep}, {clack}}};
	std::cout << "Which button do you want to press? (1-3)\n";
	int i;
	std::cin >> i;
	std::cout << "Button " << i << ' ';
	click_button(buttons[i-1]);
	std::cout << "'s\n";
}
http://ideone.com/InrKwZ
I was trying to avoid having to make a new class for ever button. There has to be a better way than having 30 new classes for 30 new buttons that's only difference is one method.

I'll try your example. It's interesting.
My example extends button adding a capability to store and change function at runtime.
Another approach would be to use templates for automatic compile0time generation.
Topic archived. No new replies allowed.