Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I use address-of operator to get a pointer to a member function?

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?

like image 285
xmllmx Avatar asked Feb 10 '17 01:02

xmllmx


People also ask

What is pointer why we use address of operator?

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 (&).

How do you call a pointer to a member function?

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);

Which operator is used in pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object.

Which operator you use to access a member of a pointer to a class?

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.


1 Answers

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.

like image 166
WhiZTiM Avatar answered Sep 19 '22 06:09

WhiZTiM