11
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) (...)’
iammilind
  • 62,239
  • 27
  • 150
  • 297
  • see : http://ideone.com/p3a5G – Geoffroy Jun 11 '11 at 15:37
  • possible duplicate of [Calling C++ class methods via a function pointer](http://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer) – Ciro Santilli新疆棉花TRUMP BAN BAD Jul 01 '15 at 09:09
  • @CiroSantilli六四事件法轮功纳米比亚威视, No both are different. Your linked question explains, `"How to call class member using function pointer?"`, While I am asking `"<...same...>, when the function pointer itself is a class member also."`. Notice that answers to both the questions are different. – iammilind Jul 01 '15 at 12:08
  • I agree that this has one extra step. but I felt it could be easily deduced once you know the function pointer syntax: `(obj.*ptr)`, just that here `ptr == (obj.ptr)`. But well, since you disagree I'll retract ;-) – Ciro Santilli新疆棉花TRUMP BAN BAD Jul 01 '15 at 12:16

3 Answers3

14

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
CB Bailey
  • 648,528
  • 94
  • 608
  • 638
  • +1, thx; it's unique; what would have happened if `obj` was a member of `B` ? :) – iammilind Jun 11 '11 at 15:39
  • @iammilind: `obj` has type `B` so it can't be a member of `B` as it would imply a recursive class definition. Can you clarify what you mean? – CB Bailey Jun 11 '11 at 15:42
  • No. even if there was a member like `obj` inside B; it won't be a problem until you have `(....)` enclosing the signature. I am clear with that problem now. So, either it will be a compile error or it will work fine. – iammilind Jun 11 '11 at 15:43
5

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

Geoffroy
  • 11,789
  • 4
  • 45
  • 92
5

The syntax is quite unnatural but a consequence of C++ precedence rules...

(obj.*obj.pf)(1, 2);
6502
  • 104,192
  • 14
  • 145
  • 251