0

I'm testing, trying to call a member function being passed as a parameter, the member function has to be one of another class. this is an example, which gives an error:

"pointer-to-member selection class types are incompatible ("B" and "A")"

This is the code, what am I doing wrong?

#include <iostream>
using namespace std;
class A {
private:
public:
    void fA(int x) {
        cout << "hello" << endl;
    }
    void fB(int x) {
        cout << "good bye" << endl;
    }
    A() {
    }
};

class B {
private:
    void (A:: * f)(int) = NULL;
public:
    B(void (A:: * f)(int)) {
        this->f = f;
    }
    void call() {
        (this->*f)(10); //What's wrong here?
    }
};
A a = A();
B b = B(&(a.fA));
B b2 = B(&(a.fB));

int main(void) {
    b.call();
    b2.call();
}
2
  • Normal member functions are static. A pointer to them is not a pointer through the class instance (as with variables). Instead, they are passed a hidden 'this' pointer on class which indicates the instance. Therefore, &(a.fA) has no meaning. Commented Aug 14, 2021 at 10:51
  • Instead of using function pointers I suggest that you look into std::funtional: en.cppreference.com/w/cpp/utility/functional/function Commented Aug 14, 2021 at 11:52

1 Answer 1

6

&(a.fA) is not legal C++ syntax. &A::fA is. As you can see, there is no object of type A anywhere of this syntax. &A::fA is just a pointer to a member function, not a pointer-to-member-together-with-an-object combo.

Now in order to call that pointer-to-member, you need an object of class A. In class B, you don't have any. You need to get one in there somehow, and call the function this way:

 (a->*f)(10);

where a is a pointer to that object of class A.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.