Function Pointer Problem

Started by
2 comments, last by DudeMiester 19 years, 6 months ago

class A
{
	void (*varFunc)();
public:
	inline void Func()
	{
		varFunc();
	}
	A(void (*myFunc)()) : varFunc(myFunc)
	{
	}
};

class B : public A
{
	void myFunc()
	{
		cout<<"Func"<<endl;
	}
public:
	B() : A(&myFunc)
	{
	}
};

int main()
{
	B Test;
	Test.Func();
}

This is what I'm trying to do. It won't work and the compiler gives me this error: error C2276: '&' : illegal operation on bound member function expression So I tried useing &B::myFunc and the compiler gave me this error: error C2664: 'A::A(void (__cdecl *)(void))' : cannot convert parameter 1 from 'void (__thiscall B::* )(void)' to 'void (__cdecl *)(void)' So is it possible to do what I'm trying to do?
[s] [/s]
I can see the fnords.
Advertisement
The signature for a class method does not match that for a non-class function. The difference is one of calling convention - __thiscall vs __stdcall - which means that they pass their parameters differently. A workaround is to make the class method static, but that can introduce certain constraints.

A more robust solution is to use a functor or function object:

struct Functor{  Functor()  {    // any initialization  }  void operator () ()  {    // do whatever  }};...Functor f;..f(); // invokes functor just like a function pointer

If you make the Functor class an interface, or at least a base class, then all classes derived from it can be invoked through polymorphic dispatch.

For reference, though: www.function-pointer.org.
Hmm...I'm not really sure what you're trying to do with varFunc(myFunc) in the constructor for class A.

Are you...trying to set it to the value of myFunc? I didn't think that you could do that with function pointers. But then again, I just recently learned how to use them, so many of the uses are, uh...Greek to me.

Still, I'll try to help as much as I can here.
Things change.
lol, I actually used functors without knowing it for my problem. See I had this problem a while ago, but I never bothered to ask about it until now. So yeah, the code I wrote as it turns out is basically just used a functor and that works fine.
[s] [/s]
I can see the fnords.

This topic is closed to new replies.

Advertisement