c++ Possible for function pointers to point to member function?

Started by
4 comments, last by Sutekh 18 years, 1 month ago
Hi, with c++ classes, I was wondering if it was possible for a function pointer to point to a member function? Thanks
Advertisement
The short answer is no. Functions in classes are not constructed in memory the same way as static (global) functions. There is extra data passed to the function to describe the object the function is to act upon. So if you have a library that gives a typedef'ed callback that you want to fill with a non-static member function, it's simply not possible.

If you're designing your own callbacks, though, the long answer is yes, according to Google.
It is possible. With a little magic.

friend a method, that'll help.
Or have a static method and make sure a pointer to this is passed in as an argument and call the regular method.

A great example of this is done at stromcode's Win32 tutorial. It completely encapsulates Win32 windows. Including the WinProc. Which is a callback method.

Stromcode's C++ Win32
You can have a member function pointer. The syntax is a bit strange but it can be done. To do this, you have to have a valid instance of the object for it to work.

Example:
typedef void (SomeClass::*MemFuncPtr)( void );

MemFuncPtr pMemFuncPtr = &SomeClass::SomeFunction;

SomeClass oSomeClass;

(oSomeClass.*pMemFuncPtr)();

SomeClass * pSomeClass = new SomeClass;

(pSomeClass->*pMemFuncPtr)();
Of course it's possible. You just have to use the ->* operator to call it.

e.g. http://www.gamedev.net/community/forums/topic.asp?topic_id=263874&whichpage=1?

Or google for "Member function pointer"
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
You must realize what the member function’s purpose is, which is to perform some action on that class or using that class's data. So if the function is not static, the function needs a class object to act on while being executed.

This can be done several ways. You may use a functor, an object which wraps a member function pointer, a pointer to an object, and overloads operator(). Another way to do this is to use a bind, available with boost::bind and boost::function.

Just something I threw together, I hope it helps.
Btw everything I have stated is just stuff I have picked up along the way.

typedef boost::function< int( int, int ) > ClassAFunc;class A{public:	int Add( int a, int b )	{		return a + b;	}};int main(){	//uses a shared smart pointer so that the binded function can never have hanging pointer	boost::shared_ptr< A > ptr( new A);	ClassAFunc func;	// boost::bind<returnType>( functionPointer, objectPointer, argument1, argument2);	//argument1 and 2 simply show where the arguments go when the binded function is called	func = boost::bind<int>( &A::Add, ptr, _1, _2 );	std::cout << func( 1, 2 ); // would print 3}

This topic is closed to new replies.

Advertisement