struct A
{
void f() {}
};
void f() {}
int main()
{
auto p1 = &f; // ok
auto p2 = f; // ok
auto p3 = &A::f; // ok
//
// error : call to non-static member function
// without an object argument
//
auto p4 = A::f; // Why not ok?
}
Why must I use address-of operator to get a pointer to a member function?
An address-of operator is a mechanism within C++ that returns the memory address of a variable. These addresses returned by the address-of operator are known as pointers, because they "point" to the variable in memory. The address-of operator is a unary operator represented by an ampersand (&).
Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object.
Simply saying: To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.
auto p1 = &f; // ok
auto p2 = f; // ok
The first is more or less the right thing. But because non-member functions have implicit conversions to pointers, the &
isn't necessary. C++ makes that conversion, same applies to static member functions.
To quote from cppreference:
An lvalue of function type
T
can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With