0

How to invoke an object method passed to a variable?

class A {
public:
    inline int f() {
        return 1;
    }
};


int main() {
    A a;

    int (A::*y)(); //'y' must be a method of 'A' class that returns 'int'
    y = &A::f; //bind 'f' method

    *y(); //how to invoke???
}

The other thread bound a method to an object field and it was invoked this way (a.*(a.x))(), but i can't find a way to do a similar thing to a simple variable.

Humberd
  • 2,794
  • 3
  • 20
  • 37

1 Answers1

2

Simply do (a.*y)();. You need the extra parantheses make the compiler resolve the pointer to member before making the function call. See operator precedence:

class A {
public:
    inline int f() {
        return 1;
    }
};


int main() {
    A a;

    int (A::*y)(); //'y' must be a method of 'A' class that returns 'int'
    y = &A::f; //bind 'f' method

    (a.*y)();
}

Demo

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • How can I get the name of the function (in this case it will be `f`) that was passed to a variable `y`? – Humberd Apr 17 '17 at 22:55
  • 1
    @Humberd, there's no portable or easy way... The current means is via `std::type_info` which would't give you the name you hope for. We hope some reflection proposals scale through for C++20 ... :-) – WhiZTiM Apr 17 '17 at 23:18