Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Function pointer to another class function

I have 2 classes

class B {
public:
    int func(int i);
};

class A {
public:
    typedef int (B::*fPtr)(int);
    void run();
    B* mB;
};

void A::run() {
    // create a pointer
    fPtr p = &(B::func);
    // invoke the function
    mB->*p(2);     <------- Compilation Error
}

What i need is to create a pointer to func() in A's run function. I get a compilation error saying that mB is not corresponding to a function with 1 argument.

please help

like image 395
Alex Kul Avatar asked Jul 21 '26 00:07

Alex Kul


1 Answers

You need to put parentheses around the function expression:

(mB->*p)(2);

But as others have pointed out, there's almost certainly a better way to do what you're trying to do.

like image 166
Sean Avatar answered Jul 22 '26 13:07

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!