   C++ Function pointer help
  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;}
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 :)   ;  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.   ;Quote:Original post by rneckelmannQuote: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!