In:
foobar(&MyClass::method);
... &
is not the "reference operator" but is the address-of operator. It takes the address of its operand.
You actually do still "have to" take the address of a free function in code such as (although implicit conversions are available):
goobar(freefunction);
There are implicit conversions available which will cause an expression such as Foo
to decay in to a pointer, but I have had much difficulty in getting GCC to accept such code error- and warning-free, in cases where MSVC has no problems.
Aside from this, there are two main differences between free functions and non-static member functions:
- Non-
static
member functions operate on an instance of a class, and there is a this
pointer which points to the class itself.
- The syntax for creating and calling through a pointer-to-free-function is different than that for a pointer-to-member-function.
In the case of the free function, the syntax is trivial(ish):
void foo(); // Function declaration
void(*f)(); // Declaration of pointer-to-function-returning-void-and-taking-no-parameters
But in the case of a pointer to a member function, the syntax is much trickier:
struct Bar
{
void DoIt()
{
}
void DoThat(int n)
{
n;
}
};
void(Bar::*thatfn)(int); // declares a pointer-to-member-function taking int returning nothing
thatfn = &Bar::DoThat; // initializes pointer to point to DoThat(int)
(bar.*thatfn)(42); // call the function