• Advertisement
Sign in to follow this  

C++ Function pointer help

This topic is 2858 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
Prefer boost::function over writing your own function storing/invocation code. It will seamlessly handle free functions versus member functions, while working across multiple compilers and platforms.

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement