Archived

This topic is now archived and is closed to further replies.

hello2k1

Callback functions & class members

Recommended Posts

Well basically what I want to do is have a callback function point to a class instance function. I know that I could just put a static prefix on the function which I want to call back, but unfortunately in my case I can''t change the class in any way. A friend of mine advised me to pass the class instance as the first parameter, and just cast the function into the callback, but the compiler seems to have a problem with the conversion. For example: class CClass{ public: void function(); } void main(){ CClass class; void (*callback)(void *); callback = class.function; callback(&class); }

Share this post


Link to post
Share on other sites
Hi

your friend was right, you can''t do this without a class instance, but you don''t need to pass it, you need to call the callback from the class instance.
Do it like this:

class CClass{
public:
void function();
}

void main(){
CClass class;
void (CClass::*callback)(void);
callback cb = class.function;
(class.*cb)();
}

this should work

------------
Runicsoft

Share this post


Link to post
Share on other sites
Woot! It compiled, thanks. Time to get down to applying it...

Edit: How would I be able to do this without defining the class type? eg. I don't know it's CClass, I just know it's some class.

[edited by - hello2k1 on August 11, 2002 7:11:16 PM]

Share this post


Link to post
Share on other sites
That isn't possible as far as i know.
A little possible workaround is to have a virtual base class and derive from it.
If you typedef the functionpointer to the base class you can call it from class instances derived from the base class.
Like this:

  
#include <stdio.h>

class BaseClass
{
public:
virtual void function() = 0;
};

class myclass: public BaseClass
{
public:
void function()
{
printf ("hello from myclass\n");
};
};

class myclass2: public BaseClass
{
public:
void function()
{
printf ("hello from myclass2\n");
};
};

typedef void (BaseClass::*CALLBACKFUNC)(void);

void main()
{
BaseClass* obj = new myclass;
BaseClass* obj2 = new myclass2;
CALLBACKFUNC cbf = obj->function;
(obj->*cbf)();
(obj2->*cbf)();
delete obj;
delete obj2;
}


the output is
hello from myclass
hello from myclass2

so you only assign the function pointer once, and you can call it from any instance of a derived class. I'm not sure if there might be problems with multiple inheritance or something, but at least the example works

------------
Runicsoft


[edited by - Burning_Ice on August 11, 2002 8:05:43 PM]

Share this post


Link to post
Share on other sites
Yea, I was thinking about that.. but changign the class/function in any way just isn''t a choice. However, I may be able to include the class. I''m going to have to finish planning it out, then I''ll get back to you.

Thanks for your help.

Share this post


Link to post
Share on other sites