Connecting Tech Pros Worldwide Help | Site Map

Pointer to member function?

Newbie
 
Join Date: Mar 2007
Posts: 1
#1: Mar 25 '07
Hi,

I'm trying to pass pointers to member functions around in my code.

The test with pointers to non-member function works fine:
Expand|Select|Wrap|Line Numbers
  1. Code:
  2.  
  3. void callOut( void (*callback)() )
  4. {
  5.     callback();
  6. }
  7.  
  8. void testOut()
  9. {
  10.     cout << "testOut hier" << endl;
  11. }
  12.  
  13. int main(int argc, char **argv)
  14. {
  15.     callOut( &testOut );
  16. }
  17.  


Now if I try it with a member function:

Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3. public:
  4.     void out()
  5.     {
  6.         cout << "A here " << endl;
  7.     }
  8. }; 
  9.  
  10. void callOut( void (A::*callback)() )
  11. {
  12.     callback();
  13.     // error: must use ‘.*’ or ‘->*’ to call pointer-to-member
  14.     // function in ‘callback (...)’
  15. }
  16.  
  17. int main(int argc, char **argv)
  18. {
  19.     A* a = new A;
  20.     callOut( &a->out );
  21.     // error: ISO C++ forbids taking the address of a bound
  22.     // member function to form a pointer to 
  23.     // member function. Say ‘&A::out’
  24. }

So gcc says it's impossible to use pointers to member function. But I found some tutorials talking about them (but didn't understood them )

Is it possible? And if yes could you please correct my example code?

Background is I'm implementing a finite state machine and the output function of the states are virtual methods of subclasses of an ABC, so pointers to member functions (of the correct derived type) seemed to do the job.
If you say pointer to member fuctions doesn't work in C++, do you know some better idiom to use for this purpose?

tank you very much!
Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Mar 25 '07

re: Pointer to member function?


try
Expand|Select|Wrap|Line Numbers
  1. //  AmemberFunc points to a member of A that takes ()
  2. typedef  void (A::*AmemberFunc)();
  3.  
  4. // pass reference to A and pointer to member function
  5. void callOut(A &a, AmemberFunc pFunc )
  6. {
  7.     (a.* pFunc)();   // call member function
  8. }
  9.  
and calling it so
Expand|Select|Wrap|Line Numbers
  1.     A a;
  2.     callOut( a, &A::out );
  3.  
have a read thru
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
Reply