C++ Creating a function, like a variable, change its body later and then call it later

Viewed 64

I'm trying to create a dummy function inside of a class, whichs' body will be changed later in int main(). And then I'd like to call this body changed func in the class. Is there a way to achieve this?

Something like this:

class Animation {
public:

    //Don't know what to write at the next line
    function<void>/*?*/ whenCompleted = []() mutable { /* Dummy func. */ };
    .
    .
    .
    void startAnimation() { /* Do stuff, then */ animationEnded(); }
    void animationEnded() { whenCompleted(); }

}score;


int main(){
    score.whenCompleted = { /* new body for whenCompleted() */ }
    score.startAnimation();
}
1 Answers

You basically have the right idea

#include <functional>
#include <iostream>
 
class Animation
{
public:
    std::function<void()> whenCompleted;
 
    void startAnimation() { animationEnded(); }
    void animationEnded() { whenCompleted(); }
};
 
int main()
{
    Animation score;
    score.whenCompleted = [](){ std::cout << "all done"; };
    score.startAnimation();
}

Will output

all done

You could also add a constructor for Animation that accepts a function to initialize whenCompleted with

Animation(std::function<void()>&& onCompleted) : whenCompleted(onCompleted) {}

which would modify main to

int main()
{
    Animation score{[](){ std::cout << "all done"; }};
    score.startAnimation();
}
Related