Functions
A similar exercise produces the
pointer-to-member syntax for member functions. A pointer to a function
(introduced at the end of Chapter 3) is defined like this:
int (*fp)(float);
The parentheses around (*fp) are
necessary to force the compiler to evaluate the definition properly. Without
them this would appear to be a function that returns an int*.
Parentheses also play an important role
when defining and using pointers to member functions. If you have a function
inside a class, you define a pointer to that member function by inserting the
class name and scope resolution operator into an ordinary function pointer
definition:
//: C11:PmemFunDefinition.cpp
class Simple2 {
public:
int f(float) const { return 1; }
};
int (Simple2::*fp)(float) const;
int (Simple2::*fp2)(float) const = &Simple2::f;
int main() {
fp = &Simple2::f;
} ///:~
In the definition for fp2 you can
see that a pointer to member function can also be initialized when it is
created, or at any other time. Unlike non-member functions, the & is
not optional when taking the address of a member function. However, you
can give the function identifier without an argument list, because overload
resolution can be determined by the type of the pointer to member.