views:

1955

answers:

4
class Foo {
public:
    Foo() { do_something = &Foo::func_x; }

    int (Foo::*do_something)(int);   // function pointer to class member function

    void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; }

private:
    int func_x(int m) { return m *= 5; }
    int func_y(int n) { return n *= 6; }
};

int
main()
{
    Foo f;
    f.setFunc(false);
    return (f.*do_something)(5);  // <- Not ok. Compile error.
}

How can I get this to work?

+1  A: 

Try (f.*do_something)(5);

Suvesh Pratapa
+9  A: 
 class A{
    public:
        typedef int (A::*method)();

        method p;
        A(){
            p = foo;
            (this->*p)(); // <- trick 1, inner call
        }

        int foo(){
            printf("foo\n");
            return 0;
        }
    };

    void main()
    {
        A a;
        (a.*a.p)(); // <- trick 2, outer call
    }
Nick D
+1 for two tricks
Thomas L Holaday
Tudok, after going through your post a second time I realized that you have given the right answer too (trick 2). Thanks.
Girish
+7  A: 

The line you want is

   return (f.*f.do_something)(5);

(That compiles -- I've tried it)

"*f.do_something" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f." prefix.

James Curran
Got it! Thanks James.
Girish
Technically, "f.do_something" returns the pointer, and the ".*" operator calls the pointer-to-member function on a class.
Todd Gardner
A: 

I think calling a non static member of the class could also be done using a static member function.

Pradip Bhojania