Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why callback functions needs to be static when declared in class

Tags:

c++

callback

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);
}
like image 662
cpx Avatar asked Mar 08 '10 10:03

cpx


People also ask

Why do we need static member function in class?

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

What is the purpose of static functions?

Static functions are used to invoke a class code when none of its instance exists( in more purer oop languages). Static functions can change static variables. Show activity on this post. Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.

What happens when we declare a function as static?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

Why callback functions are needed?

Need of Callback Functions. We need callback functions because many JavaScript actions are asynchronous, which means they don't really stop the program (or a function) from running until they're completed, as you're probably used to. Instead, it will execute in the background while the rest of the code runs.


1 Answers

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 the pointer to the function to be able to call it.

Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).

like image 107
Klaim Avatar answered Oct 23 '22 12:10

Klaim