How do I declare and use a pointer to a class member function? (Top)
The syntax is similar to a regular function pointer, but you also have to specify the class name. Use the. * And-> * operators to call the function pointed to by the pointer.
Collapse
Class cmyclass
{
Public:
Int addone (unsigned N) {return n + 1 ;}
Int addtwo (unsigned N) {return n + 2 ;}
};
Main ()
{
Cmyclass myclass, * pmyclass = & myclass;
INT (cmyclass: * pmethod1) (unsigned); // full declaration syntax
Pmethod1 = cmyclass: addone; // sets pmethod1 to the address of addone
Cout <(myclass. * pmethod1) (100); // callmyclass. addone (100 );
Cout <(pmyclass-> * pmethod1) (200); // callpmyclass-> addone (200 );
Pmethod1 = cmyclass: addtwo; // sets pmethod1 to the address of addtwo
Cout <(myclass. * pmethod1) (300); // callmyclass. addtwo (300 );
Cout <(pmyclass-> * pmethod1) (400); // callpmyclass-> addtwo (400 );
// Typedef a name for the function pointer type.
Typedef int (cmyclass: * cmyclass_fn_ptr) (unsigned );
Cmyclass_fn_ptr pmethod2;
// Use pmethod2 just like pmethod1 abve ....
}
The line collapse
INT (cmyclass: * pmethod1) (unsigned );
Pmethod1 is a pointer to a function in cmyclass; that function takes an unsigned parameter and returns an int.
Note that cmyclass: addone is very different from cmyclass: addone (). The first is the address of the addone method in cmyclass, while the second actually callthe method.