Thursday, November 15, 2007

Why non-static member functions are not used as callback functions?

Here’s a small but useful tip. All of us are familiar with call-back functions. Normally in C++, if we are using a class member function as callback function, it should be a static function. Below mentioned is the reason for this :

There's an invisible parameter (this) required on the stack when calling class member functions. Windows is fundamentally C based, and doesn't know anything about objects and "this" pointers, so the callbacks don't use them. You can use a static member function or a simple global function as a callback, because they're not associated with a specific class instance, so no "this" is used when calling them. In such cases if we want to access class member functions, the “this” pointer is usually passed to callback functions, like we normally do.

No comments: