This is what I am trying to do:
class A {
public:
void(*fPtr)();
};
class B {
int ib = 2;
public:
void memf() {
printf("ib = %i\n", ib);
}
};
class C {
int ic = 6;
public:
void memf() {
printf("ic = %i\n", ic);
}
};
int main()
{
B b;
C c;
A a1;
A a2;
a1.fPtr = b.memf;
a2.fPtr = c.memf;
}
Basically a class that has a function pointer. This function pointer can be directed to a normal or member function.
The error I get in Visual Studio however:
Error C2440 '=': cannot convert from 'void (__thiscall B::* )(void)' to 'void (__cdecl *)(void)'
Error C2440 '=': cannot convert from 'void (__thiscall C::* )(void)' to 'void (__cdecl *)(void)'
Error C3867 'B::memf': non-standard syntax; use '&' to create a pointer to member
Error C3867 'C::memf': non-standard syntax; use '&' to create a pointer to member
I know this might seem like a duplicate, maybe it is. I failed to use solutions that were recommended like using <functional>
.
Can somebody show me how to do it right so I can understand what I was doing wrong? I would also like to know why the standard way doesn't work.
In other words: Correct my code ;) I would really appreciate it.
The easiest way to see why this is going to cause problems is to ask - if you did call the function pointed at by the function pointer, what would the receiver object be? For example, suppose you point at B::memf
and then call it through fptr
. That function needs to operate relative to a B
object so that it can read the value of that B
object’s ib
field. But there’s no way for us to figure out what B
object to use - bad times!
The reason that (nonstatic) member functions are different than free functions is that they have an implicit parameter representing the receiver object, and so when calling that function there needs to be some way to specify what that object is.
The other answers on this site should be able to provide some information about some possible strategies for fixing this issue, but hopefully this sheds some light on what that issue is in the first place.