Search code examples
c++classsyntaxpointer-to-membermember-functions

Pointer to methods problems


Well, as I stated in the question: pointers to members methods

My question: msvc++ is throwing me errors.

If we have:

class A 
{
    bool one, two;
    typedef void (A::* RunPtr)(int);
public:
    RunPtr Run;

    A() : one(false), two(false)
    {
        Run = &A::RunOff;
    }
    void SetOne(bool value)
    {
        one = value;
    }
    void SetTwo(bool value)
    {
        two = value;
    }
    void SetOnOrOff()
    {
        if (one || two)
            Run = &A::RunOn;
        else
            Run = &A::RunOff;
    }

    void RunOn(int param)
    {
        //RunOn stuff here
        cout << "RunOn: " << param << endl;
    }

    void RunOff(int param)
    {
        //RunOff stuff here
        cout << "RunOff: " << param << endl;
    }
};

Now I want to call, the public Run ptr from outside the class. Say:

A a = new A();
a->*Run(10);    // notice that 10 is an int

I have tried two ways:

a->Run(10)      // Option 1
a->*Run(10)     // Option 2

Option 1 throws me

term does not evaluate to a function taking 1 arguments

Option 2 throws me

function does not take 1 argument

These two errors doesn't let me call the method pointer.


Solution

  • The correct syntax to call the member Run (which holds the pointer to the member function) with argument is

    A* a = new A();
    (a->*(a->Run))(10);
                   ^^^ ---------> argument(s)
         ^^^^^^^^^ -------------> class member "Run"
    ^^^^^^^^^^^^^^--------------> call to member function pointer syntax
    
    // delete a after use
    

    Note that the a is a pointer to the class A. You need to first dereference the pointer to access its member (i.e. a->Run). Now you need the call to pointer to member function pointer syntax with dereferencing the pointer a once again.

    However, call would be much easier using std::invoke (Since ).

    #include <functional>   // std::invoke
    
    std::invoke(a->Run, a, 10);
    

    (See a Demo)