1
class C{ public: int i(){return 3;} }; void memfn(int (C::* const & func)()){} void fn(int (* const & func)()){} int main() { fn(&foo); //Works fn(foo); //Works memfn(&C::i); //Works memfn(C::i); //Doesn't Work } 

When passing a function pointer as a parameter, the address-of operator is optional on the function. Why does it not work if removed on a member function?

2
  • Because that's the rules of the language. There is a special rule for functions but no corresponding special rule for member functions. Commented Jan 27, 2022 at 3:51
  • The rule that allows the name of a function to be converted to a pointer (so you don't need the &) is actually an exception in the language. What you say about member functions is actually the "normal" and being able to remove the & on non-member functions is the exception. Commented Jan 27, 2022 at 4:37

1 Answer 1

2

There is an implicit conversion from global function references, or static member function references, or non-capturing lambdas, to function pointers. This is for capability with C.

But such implicit reference-to-pointer conversions are not for non-static member functions (and capturing lambdas!), because they need an implicitly passed this pointer to work, the conversion just lacks that thing.

In your case, if we make i() static, then it can be passed to fn either by reference or by address.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.