Sign in to follow this  
Endar

pointer to function - pointer to member function

Recommended Posts

Just for fun, I'm trying to convert a pointer to a member function to a pointer to a non-member function.
class A
{
public:
	int s;

	A():s(5)
	{	}

	void func()
	{
		std::cout << s << std::endl;
	}
};

int main()
{
	void (*f)(A*);

	A a;

	f = (void (__cdecl*)(A*)) A::func;

return 0;
}

I got to this point, and, it doesn't work:
error C2440: 'type cast' : cannot convert from '' to 'void (__cdecl *)(class A *)'
And I'm not sure what to try now.

Share this post


Link to post
Share on other sites
Don't bother. Pointers to member functions have a very different structure than normal pointers to functions. Pointer to member functions can be up to four times the size of a pointer to a normal function, so trying to stuff it in will lose data.

Share this post


Link to post
Share on other sites
As I understand it, taking the address of a class method may or may not actually point to the address of the function. It could, instead, point to...something else, I assume =).

Read the C++ FAQ Lite, it explains much better than I. Click here for the best warning label.

EDIT: Also, I noticed that in your original example you're trying to use the __cdecl calling convention -- if this was in C, that would be closer to the "correct" solution, though, as above, it may or may not point to what you actually want. In C, methods and function pointers are different because of calling convention; in C++, they're different because of the way they're represented (having a really hard time expressing this, considering I don't fully understand it).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this