Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Member functions as callbacks

Status
Not open for further replies.

Leroy1981

Programmer
Jul 22, 2002
46
US
When I try to use a typical function as a callback everything works fine but if i try it with a member function of a class that has the same return type and parameter list i get a cannot cast from (classname::) (function parameters) to (function parameters).

the borland error code is e2031 if that helps.

 
make it static.

Ion Filipski
1c.bmp
 
Problem is that one more parameter is passed to every member-function. It's a this-pointer which is hidden from you, but will spoil argument types and order, so that's why you CAN NOT use member-functions as callbacks.
Use static or global fn. instead.
 
You can most certainly use (non-static) member functions as callbacks. You have to pass the object you're calling it on, of course.

The STL has some stuff in the <functional> header for doing just that, check out something called mem_fun (I believe) in some STL reference libraries.

Also, Boost ( has a callback function library that's kind of in flux right now, but will become part of the next C++ Standard (in some form or another). It has member function callback capability.

You could, of course, just use a function object containing a reference to the object whose member function you want to call.
 
by the way, If you want to make a member WndProc, you can attach a pointer by doing:

class xxx
{
static LRESULT CALLBACK WndProc(HWND, int, WPARAM, LPARAM);
LRESULT WndProc(int msg, WPARAM wParam, LPARAM lParam)
{
handle messages there
....
}
};
xxx
{
static LRESULT CALLBACK WndProc(HWND, int, WPARAM, LPARAM);
};
LRESULT CALLBACK XXX::WndProc(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam)
{
xxx* mObj = (xxx*)GetWindowLong(hWnd, GWL_USERDATA);
if(mObj)return mObj->WndProc(msg, wParam, lParam);
return DefWindowProc(hWnd, msg, wParam, lParam)

}

......
create window there

xxx myXxx;
hWnd = .......
SetWindowLong(hWnd, GWL_USERDATA, (LONG)&myXxx);



Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top