Passing a void function as an argument to another function

I am trying to pass the void function to another void function, unsuccessfully so far. So I created this function inside an ExitButton class like this. ExitButton.h:

class ExitButton{

 void setup(void (*_setup));

};

Then I include this class in another class like this. ofApp.h:

include "ExitButton.h"
class ofApp : public ofBaseApp{

 void update();
 void setup(); 
 StartButton *startButton;

}

So, in myApp.cpp, I want to call the update function as follows:

void ofApp::update(){


exitButton->setup(setup()); // This throws me the following error: Cannot initialize a parameter of type 'void (*)' with an rvalue of type void
    }

So, I assume that I can only pass the void function, which is a pointer? Is it possible to pass the void function as a parameter to another function?

0
source share
1 answer

This is probably what you want:

#include <iostream>
using namespace std;

class ExitButton{
public:
    void setup(void (*_setup)())
    {    
        _setup(); // we call the function pointer
    };
};    


void setup() // this is a void function
{
    cout << "calling void setup()" << endl;
}

int main()
{
    ExitButton eb;
    eb.setup(setup); // use a void function as a parameter
}
+2
source

All Articles