C++ Function Pointers

Pointers to Member Functions are one of C++'s more rarely used features, and are often not well understood even by experienced developers. This is understandable, as their syntax is necessarily rather clumsy and obscure.

Sample Code in 'C' language

void Foo( int anInt, double aDouble );
void Bar()
{
void (*funcPtr)( int, double ) = &Foo;
(*funcPtr)( 1, 2.0 );
}

Sample Code in 'C++' language

class Foo
{
public:
double One( long inVal );
double Two( long inVal );
};

void main( int argc, char **argv )
{
double (Foo::*funcPtr)( long ) = &Foo::One;
Foo aFoo;
double result =(aFoo.*funcPtr)( 2 );
return 0;
}

Details:

For regular function pointers, it is optional to use the address-of operator & when taking the address of a function, but it is required for taking the address of member functions.

To declare a pointer to member function, you give the prototype of a function it can point to, as before, but the name of this function is replaced by a construction that scopes the pointer - you give it the name of the class whose member functions it can point to, as (ClassName::*pointerName).

Note that a given member function pointer can only point to functions that are members of the class it was declared with. It cannot be applied to an object of a different class even if it has member functions with the same signature.

You dereference a member function pointer by using .* or ->*, supplying a reference or pointer to an object on the left, as appropriate, and the function pointer on the right.

Ref:
http://www.goingware.com/tips/member-pointers.html

http://linuxquality.sunsite.dk/articles/memberpointers/

http://www.geocities.com/varunhostel/TechnicalArticles/PointerArticle/PointerArticle_Intro.html?reload_coolmenus

http://stackoverflow.com/questions/402992/passing-function-pointers-in-c