The most important thing to understand is that the type is different from that of a pointer to a C-style (non-member) function. Simply understanding that they are completely different and have incompatible types will prevent the most common and dangerous errors with pointers to member functions. A pointer to the nonstatic member function with signature void Fred::f(int) has type void(Fred::*)(int). In particular, the type of the pointer to a nonstatic member function includes the class of the member function because nonstatic member functions have an implicit parameter that points to the object (the this pointer). Here's an example. #include <iostream> using namespace std; class Fred { public: void f(int i) throw(); void g(int i) throw(); void h(int i) throw(); }; void Fred::f(int i) throw() { cout << "Fred::f(int); i=" << i << '\n'; } void Fred::g(int i) throw() { cout << "Fred::g(int); i=" << i << '\n'; } void Fred::h(int i) throw() { cout << "Fred::h(int); i=" << i << '\n'; } typedef void(Fred::*FredMemberPtr)(int); Note the use of the typedef. Because of the rather obscure syntax of pointers to nonstatic member functions, it is highly recommended that a typedef be used to represent the pointer type. In the following example, a pointer p is created to point to Fred::g. This pointer is then used to call the member function. void sample(Fred& x, FredMemberPtr p) throw() { (x.*p)(42); } <-- 1 int main() { FredMemberPtr p = &Fred::g; Fred x; sample(x, p); }
The output of this program is as follows. Fred::g(int); i=42 A pointer to a nonstatic member function of class Fred has a totally different type from a pointer to a function. For example, the pointer type void(Fred::*)(int) is totally different from the pointer type void(*)(int). Do not use a cast to try to convert between the two types. You have been warned. A pointer to a static member function of class Fred has the same type as a pointer to a C-like function. In other words, a C-like function or static member function can be converted to the same pointer to function type, such as void(*)(int). But a pointer to a nonstatic member function cannot be converted to a normal pointer to a function type. |