Search code examples
c++function-pointersmember-pointers

is there a use for &func or class::func in c++?


This seems inconsistent. Why do we use &Example::func instead of Example::func? is there a use for Example::func or &exampleFunction? it doesnt seem like we can make a reference to a function so that rules out Example::func. and i cant think of a way to use &exampleFunction since exampleFunction already returns a pointer.

#include <iostream>
class Example {
public:
    void func() { std::cout <<"print me\n"; }
};
void exampleFunction() { std::cout << "print me too\n"; }
typedef void (Example::*ExampleFunc_t)(); 
typedef void (*ExampleFunction_t)();
int main()
{
    Example e;
    ExampleFunc_t     f  = &Example::func;
    ExampleFunction_t f2 = exampleFunction;
    (e.*f)();
    f2();
    return 0;
} 

Solution

  • Because that's how the standard defines pointers to functions.

    You actually always have to use the address operator & to get a pointer to a function, but for regular functions and static member function, an implicit conversion from function to pointer-to-function is defined in the standard.

    This is not defined for a (non static) memberfunction because you can't obtain an lvalue to a non static memberfunction.

    From the C++ standard:

    4.3 Function-to-pointer conversion

    1. An lvalue of function type T can be converted to an rvalue of type “pointer to T .” The result is a pointer to the function.

    with footnote 52:

    This conversion never applies to non-static member functions because an lvalue that refers to a non-static member function cannot be obtained.

    I think that they'd rather only allow &function, for consistency reasons, but that the implicit conversion is simply an artifact of the C heritage...