Pointer to member function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pheres
    New Member
    • Mar 2007
    • 1

    Pointer to member function?

    Hi,

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

    The test with pointers to non-member function works fine:
    Code:
    Code:
    
    void callOut( void (*callback)() )
    {
    	callback();
    }
    
    void testOut()
    {
    	cout << "testOut hier" << endl;
    }
    
    int main(int argc, char **argv)
    {
    	callOut( &testOut );
    }


    Now if I try it with a member function:

    Code:
    class A
    {
    public:
    	void out()
    	{
    		cout << "A here " << endl;
    	}
    }; 
     
    void callOut( void (A::*callback)() )
    {
    	callback();
    	// error: must use ‘.*’ or ‘->*’ to call pointer-to-member
    	// function in ‘callback (...)’
    }
    
    int main(int argc, char **argv)
    {
    	A* a = new A;
    	callOut( &a->out );
    	// error: ISO C++ forbids taking the address of a bound
    	// member function to form a pointer to 
    	// member function. Say ‘&A::out’
    }

    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!
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    try
    Code:
    //  AmemberFunc points to a member of A that takes ()
    typedef  void (A::*AmemberFunc)();
     
    // pass reference to A and pointer to member function
    void callOut(A &a, AmemberFunc pFunc )
    {
    	(a.* pFunc)();   // call member function
    }
    and calling it so
    Code:
    	A a;
    	callOut( a, &A::out );
    have a read thru
    http://www.parashift.c om/c++-faq-lite/pointers-to-members.html

    Comment

    Working...