Zebrafish
Zebrafish

Reputation: 13886

Trying to call a member function pointer won't work

I know member function pointers are a bit tricky, and I can call it if the function pointer isn't a member of the class itself, but can't seem to do it if it's a member of the class:

struct Window
{
    virtual void handleEvent() {};
    void (Window::*pHandleEvent)();
};

int main()
{
    Window w;
    void (Window::*fnptr)() = &Window::handleEvent;
    (w.*fnptr)(); // Works fine calling a local func ptr
    w.pHandleEvent(); // Calling its own member pointer doesn't work
    // Err: Expression preceding parentheses of apparent call must have
    // (pointer-to) function type
    (w.*pHandleEvent)();    // Doesn't work
    //Err: identifier "pHandleEvent" is undefined
    (w.*Window::pHandleEvent)();    // Doesn't work.
    // Err: A non-static member reference must be relative to a specific object.
}

Upvotes: 0

Views: 94

Answers (2)

With C++17 you can just rely on std::invoke for all your pointer to member needs:

std::invoke(w.pHandleEvent, w);

First argument is the pointer to member, the second is the object, or a pointer to it. And all the syntactical business is taken care of for you.

Upvotes: 1

Davis Herring
Davis Herring

Reputation: 39768

You need to specify two Window objects: the one whose pointer to use and the one on which to call the method. If they’re the same, it’s

(w.*w.pHandleEvent)();

Note the precedence: if you instead have A Window::*ptm; and want a member of the A object, it’s (w.*ptm).a_member.

Upvotes: 4

Related Questions