How to call non-static member function from static member function

Hi, I’m trying to call a non-static member function from a static member function in OF.
What would be the easiest way to do it?

For example, if I want to call update() from staticFunction(), how can I do it?
Thank you so much.

void ofApp::setup(){
    
    staticFunction();
}

void ofApp::staticFunction(){
    
    update(); //error : call to non-static member function without an object argument
}

Hi there,

The main issue here is that static functions need to call an instance of an object. There are two ways to do that, a) either you turn ofApp into a singleton and call getInstance() in the static function. Or b) you modify the static function so that it gives you a pointer to the ofApp instance:

If you can modify the staticFunction to pass a pointer to ofApp, then you could do something like:

class ofApp: public ofBaseApp{
....

static void staticFunction(void * userData);
void update(); //non Static Function
}

///cpp
void ofApp::staticFunction(void * userData) {
    auto app = (ofApp*)userData;
    app->update();
}

You will find more answers in stackoverflow about this:

I had a similar issue (question 2) which Arturo solved brilliantly:

1 Like

Hey @Jordi Thank you so much for your help! I got it working.
I could not really understand the answers from stackoverflow but your example code made me understand how to apply it in OF. :slight_smile:

//--------------------------------------------------------------
void ofApp::setup(){
 
    staticFunction(this);
}

void ofApp::nonStaticFunction(int a) {
    
    cout << "nonStaticFunction Called : " << a << endl;
}

void ofApp::staticFunction(void * data) {
    auto app = static_cast<ofApp*>(data);
    app->nonStaticFunction(13);
} 

result :

nonStaticFunction Called : 13

1 Like