Sign in to follow this  
denebo

C++ Function pointer help

Recommended Posts

denebo    122
I'm trying to simulate (without the use of a GUI) a simple button that stores a function and executes it when pressed. The program compiles correctly, but then gives this error: Unhandled exception at 0xcccccccc in Testing.exe: 0xC0000005: Access violation. Here's the code:
#include <iostream>

using namespace std;

class Button
{
public:
	void (*function_) ();

	Button(void (*function) ())
	{

	}

	void click()
	{
		function_();
	}
};

void printLine()
{
	cout << "Button clicked!\n";
}

int main()
{
	Button b1(printLine);
	b1.click();

	return 0;
}

Share this post


Link to post
Share on other sites
rneckelmann    109
Quote:

void (*function_) ();



Button(void (*function) ())

{



}


You never actually store the function pointer you pass to the constructor. Either add function_ = function; somewhere in the constructor or do like this:


...

Button(void (*function)()) : function_(function)
{

...


But anyway, you might want to consider making a button base class instead with an "onclick" (or similar) virtual function. C++ supports virtual functions so we don't have to fiddle too much with function pointers :)

Share this post


Link to post
Share on other sites
denebo    122
Quote:
Original post by rneckelmann
Quote:

void (*function_) ();



Button(void (*function) ())

{



}


You never actually store the function pointer you pass to the constructor. Either add function_ = function; somewhere in the constructor or do like this:


...

Button(void (*function)()) : function_(function)
{

...


But anyway, you might want to consider making a button base class instead with an "onclick" (or similar) virtual function. C++ supports virtual functions so we don't have to fiddle too much with function pointers :)


...oh, I didn't even notice I hadn't stored the function hahah.

Thanks for the replies!

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