As I understand it, methods are really just functions with an implicit extra parameter (the this pointer), and static methods are the pretty much the same as free functions.
But there seem to be some differences between methods and functions; for example, when passing a function as an argument, why does the reference operator & have to be used on methods, but not on free functions?
foobar(&MyClass::method);
goobar(freefunction);
What other subtle technical differences are there between methods and free functions?
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):
There are implicit conversions available which will cause an expression such as
Footo 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:
staticmember functions operate on an instance of a class, and there is athispointer which points to the class itself.In the case of the free function, the syntax is trivial(ish):
But in the case of a pointer to a member function, the syntax is much trickier: