Hello

#include <iostream>

#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))

class Fred;
typedef int (Fred::*FredMemFn)(char x, float y);
class Fred
{
private:
FredMemFn m_fn;

public:
int f(char x, float y);
int g(char x, float y);
int h(char x, float y) { std::cout << "Fred's h()" << std::endl; return
0;}
int i(char x, float y);
void SetFN(FredMemFn f) { m_fn = f; }
void carry()
{
CALL_MEMBER_FN(*this, m_fn)('x', 1);
}
};


class CMyFred : public Fred
{
public:
int x(char a, float b)
{
std::cout << "MyFred's x()" << std::endl;
} void test();
};

void CMyFred::test()
{
// this works
SetFN(Fred::h);

// this doesn't <-- how to make it work? w/o casting
SetFN(x);
}

int main()
{
CMyFred f;

f.test();

f.carry(); // calls Fred's m_fn()

return 0;
}

How can I make this code work if I want class Fred/carry() to call handlers
set in CMyFred ?

If typedef int (Fred::*FredMemFn)(char x, float y) is a pointer to a Fred
member function, won't a member function in CMyFred (subclass of Fred) with
same signature be accepted?

It seems that if I change the code in CMyFred::test() from:
SetFN(x);
to
SetFn((FredMemFn)x);

then the program compiles.
Any way to tell it to accept w/o this typecast?

On clc++ they reported to me that another compiler accepts the original code
w/o complaints.


Regards,
Elias

Re: help with member functions as callbacks by lallous

lallous
Wed Apr 28 02:32:51 CDT 2004

Hello Michael

"Michael Böhnisch" <anonymous@discussions.microsoft.com> wrote in message
news:B21F3394-4E46-49C8-A53D-EE4FF2833BCE@microsoft.com...
> Hi!
>
> A class member function is different to a normal function - there is a
hidden argument that denotes the current object and can be accessed as
"this", you probably know that already. However, for class hierachies things
are not as simple and there are things that cannot be inherited. The
compiler has know to which class in a hierarchy a 'this' pointer belongs to
be able to call methods properly, depending on whether they are in some base
class or in the current class.
>
> Thus, your Fred::*FredMemFn member variable is only able to store pointer
to members of Fred, not pointers to members of CMyFred. The cast is
dangerous in my opinion, it will fake a "Fred" where in fact a "CMyFred" is
present - with different function tables. Depending how this is implemented
by a compiler, bad run-time crashes lurk behind the corner.
>

I thought that because CMyFred inherits from Fred class then passing
callbacks in that way is OK.

> Maybe a virtual member function in Fred would do the trick for you?
I want to add an unlimited number of callbacks having the same defined
signature.

Any idea?

--
Elias