Daniel
Daniel

Reputation: 267

C++ - calling a member function of another class using a pointer

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();
}

Upvotes: 0

Views: 449

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120229

&(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.

Upvotes: 6

Related Questions