Can you pass a function so you can later call it?

Question

I want to have objects with one method which calls a function (but every object should have a different function to call). I will try to show you what I mean by showing an example:

class Human
{
    public:
        void setMyFunction(void func);  // specify which function to call
        void callMyFunction();  // Call the specified function
};

void Human::setMyFunction(void func)    // ''
{
    myFunction = func;
}

void Human::callMyFunction()    // ''
{
    myFunction();
}

void someRandomFunction()   // A random function
{
    // Some random code
}

int main()
{
    Human Lisa;     // Create Object
    Lisa.setMyFunction();   // Set the function for that object
    Lisa.callMyFunction();  // Call the function specified earlier
}

This code (obviously) doesn't work but I hope you understand what I am trying to accomplish.

MfG, TPRammus


Show source
| function   | class   | object   | c++   2017-01-05 21:01 2 Answers

Answers ( 2 )

  1. 2017-01-05 21:01

    You might use std::function.

    #include <functional>
    
    class Human
    {
        std::function<void()> mFunc;
    public:
        void setMyFunction(std::function<void()> func) { mFunc = func; }
        void callMyFunction() { if (mFunc) mFunc(); }
    };
    

    Demo

  2. 2017-01-05 21:01

    I would suggest using a simple function pointer. Just do this:

    class Human
    {
        public:
            using func_t = void (*)(); 
            void setMyFunction(func_t f) {
                 func = f;
            }
            void callMyFunction() {
                 func();
            }
         private:
            func_t func;
    };
    

    The reasons why one might prefer function pointers to std::function are:

    • Performance. Calling std::function tends to be slower, than calling a function by pointer.
    • std::function needs truly ugly syntax when one needs to bind it to an overloaded function.

    Example:

    void foo();
    void foo(int x = 0);
    
    void check() {
      Human h;
      h.setMyFunction(&foo);
    }
    

    Will fail to compile.

◀ Go back