Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke pointer to member function when it's a class data member?

struct B
{
  void (B::*pf)(int, int);  // data member
  B () : pf(&B::foo) {}
  void foo (int i, int j) { cout<<"foo(int, int)\n"; } // target method
};

int main ()
{
  B obj;
  // how to call foo() using obj.pf ?
}

In above test code, pf is a data member of B. What's the grammar rule to invoke it ? It should be straight forward, but I am not getting a proper match. e.g. If I try obj.*pf(0,0); then I get:

error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘pf (...)’, e.g. ‘(... ->* pf) (...)’
like image 792
iammilind Avatar asked Jun 11 '11 15:06

iammilind


People also ask

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

How do you access a class data member with a pointer?

We can define pointer of class type, which can be used to point to class objects. Here you can see that we have declared a pointer of class type which points to class's object. We can access data members and member functions using pointer name with arrow -> symbol.

Is it possible to create a pointer to member function of any class?

Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object.

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

To access members of a structure through a pointer, use the arrow operator.


2 Answers

Like this:

(obj.*obj.pf)(0, 1);

Member access (.) has a higher precedence than a pointer to member operator so this is equivalent to:

(obj.*(obj.pf))(0, 1);

Because function call also has higher precedence than a pointer to member operator, you can't do:

obj.*obj.pf(0, 1) /* or */ obj.*(obj.pf)(0, 1)

As that would be equivalent to:

obj.*(obj.pf(0, 1)) // grammar expects obj.pf to be a callable returning a
                    // pointer to member
like image 156
CB Bailey Avatar answered Sep 21 '22 03:09

CB Bailey


pf is a method pointer, and you want to invoke the method it points to, so you have to use

(obj.*obj.pf)(1, 2);

It says the object obj you invoke the method pointed by pf

See result here :

http://ideone.com/p3a5G

like image 22
Geoffroy Avatar answered Sep 19 '22 03:09

Geoffroy