Jack  Chin
Jack Chin

Reputation: 525

why can get address of member function by class type

I met this code:

 auto f3 = std::bind(&Foo::print_sum, &foo, 95, _1);

in the previous code, we can apply the address operator to a member function while there is no instance object been created, how can that be possible?

Upvotes: 0

Views: 217

Answers (3)

eladm26
eladm26

Reputation: 563

of course you need to have an instance of type Foo called foo, because the member function Foo::print_sum is bound to foo .

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477040

The type system of C++ contains a lesser-known category of types which are pointers to members. Given any class type C and any object or function type T, there is a pointer-to-member type T C::*. Values of these types can be obtained by applying the address-of operator to the qualified name of a class member. For example:

 struct Foo;

 int Foo::* pi;                  // C = Foo, T = int
 void (Foo::* pf)(bool, int);    // C = Foo, T = void(bool, int)

 struct Foo {
     int a;
     int b;
     void f(bool, int);
     void g(bool, int);
 };

 pi = &Foo::a;
 pf = &Foo::f;

The member pointer itself only selects a class member abstractly, unrelated to any class instance. To actually use the pointer, you need a class instance, and the member-dereference operator .*:

Foo x;

int n = x.*pi;     // gets x.a
(x.*pf)(true, n);  // calls x.f(true, n)

pf = &Foo::g;
(x.*pf)(true, n);  // calls x.g(true, n)

(The parentheses in the call expression through the pointer-to-member pf are necessary because otherwise the expression a.*b(c) means a.*(b(c)). This is occasionally a point of confusion for new users.)

Don't confuse a pointer-to-member to an object member with a pointer to the actual object!

int * p = &(x.*pi);   // p = &x.a

Here p points to the actual int subobject x.a and is an ordinary object pointer, whereas pi is a pointer-to-member that abstractly selects the Foo::a member of a Foo object.

Upvotes: 5

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

Taking the address of Foo's member function gives you a pointer to member function. This type is completely independent of any Foo object. If you're going to actually call the function, you need to provide a Foo object. In this case, the this parameter of Foo::print_sum is being bound to &foo with std::bind.

Upvotes: 0

Related Questions