tags:

views:

253

answers:

6

I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why?

#include <iostream>
using std::cout;
using std::endl;

class Test
{
public:
    Test() {}

    void my_func(void (*f)())
    {
        cout << "In My Function" << endl;
        f(); //Invoke callback function
    }

    static void callback_func()
    {cout << "In Callback function" << endl;}
};

int main()
{
    Test Obj;
    Obj.my_func(Obj.callback_func);
}
+8  A: 

A member function is a function that need a class instance to be called on. Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes.

A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get teh pointer to the function to be able to call it.

Take a look to std::tr1::function or boost::function, it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback.

Klaim
+3  A: 

Callbacks need to be static so that they don't have an implicit this parameter as the first argument in their function signature.

Paul R
A: 

If you use function pointers, the runtime environment can't pass a reference to an instance when calling the function. But you may use std::mem_fun<>, in to use functors and member methods.

Seb
+1  A: 

It needs to be static so that the function signature matches. When a member function is called, a hidden parameter is included in the call (i.e. the "this" pointer). In static member functions the this pointer is not passed as a parameter.

waffleman
+1  A: 

Non-static methods require a 'this' instance, and can only be called upon an object instance.

However, it is possible to use non-static callbacks, but they are syntactically much harder to write. See http://www.newty.de/fpt/callback.html#member for an explanation.

Patrick
A: 

Marshal Cline gives you the complete answer here . The whole section contains everything you need to know.

daramarak