densha
densha

Reputation: 183

Class design to call member function of another class

I am trying to design two class, such that I can call a member function of other class from the other class and pass a string argument.

For example if I have two classes classA and classB. I want to be able to call from Class::doSomething method the ClassB::ClassB_doit method.

I have attempted via ClassA registerCallback to pass the ClassB::classB_doit() method and store it in a reference to class B.

I have tried in the attached code. However, I am not sure how to achieve this. Could someone point me in the correct direction?

#include <iostream>
#include <string>

class classB;

class classA {
public:
    classA ();
    ~classA ();
    void doSometing(std::string s) {
        x ();  // call member function in defined via registerCallback
    }
    void registerCallback(classB &t) {
        x = t;  // Store reference to member function
    }
private:
    classB & x;
};

class classB {
public:
    classB ();
    ~classB ();
    void classB_doit (std::string name) {
        std::cout << name << std::endl;
    }
};
int main(int argc, const char * argv[]) {

    classA A = classA();
    classB B = classB();
    A.registerCallback (B.classB_doit);
    A.doSometing("hello");   // Just to test call doSometing to force classB::classB_doit to be call
    return 0;
}

Upvotes: 1

Views: 65

Answers (1)

xskxzr
xskxzr

Reputation: 13040

You can use pointer to member function. In addition, reference must be bound during initialization and the object to which it is bound cannot be changed, so you can use pointer instead.

class classA {
public:
    classA ();
    ~classA ();
    void doSometing(std::string s) {
        (x->*p)(s);  
    }
    void registerCallback(classB &t, void (classB::* _p)(std::string)) {
        x = &t;  
        p = _p;
    }
private:
    classB* x; // pointer instead of reference
    void (classB::* p)(std::string); // store pointer to member function
};

You can register the object and the member function like this:

A.registerCallback (B, &classB::classB_doit);

Upvotes: 1

Related Questions