Gulaev Valentin
Gulaev Valentin

Reputation: 595

Pointer to method from another class

I have MyFunc in one h file, and MyClass1 in another h. And want call some methods from MyFunc when MyClass1 have not Null pointer to MyFunc methods. Code work for OnIncCall, but how I can point MyClass1.MyDo to MyFunc.MyDo ?

void OnIncCall()
{
    std::cout << "I'm happen " << std::endl;
}

class MyFunc
{
public:
    void MyDo() 
        {
            std::cout << "I'm happen " << std::endl;
        };
};

class MyClass1
{
public:
    MyClass1();
    void (*MyDo)();
};

MyClass1::MyClass1()
{
    MyDo = NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
    MyClass1 a;
    MyFunc b;
    //a.MyDo = b.*MyDo;
    a.MyDo = OnIncCall;
    if (a.MyDo != Null){    
        a.MyDo();
    }
}

Upvotes: 1

Views: 1198

Answers (1)

xryl669
xryl669

Reputation: 3614

If the method is non static, you need an instance to the object so you can call a pointer-to-method on it.

In your proposed interface, you can not call MyFunc.MyDo since you don't have a pointer (or a reference) to MyFunc's instance.

So basically, this should work:

class MyFunc; // Forward declare MyFunc class

class MyClass1 
{
public:
    MyFunc & obj; // Could be a pointer too
    void (MyFunc::*MyDo)(); // Pointer to method

    void myDo() { (obj.*MyDo)(); } // Call pointed method

    void setPtr(void (MyFunc::*ptr) ()) { MyDo = ptr; } // Set the pointer to method

    // Initialize the reference to MyFunc's instance
    MyClass1(MyFunc & obj) : obj(obj) {}
}; 

In another file, your main function would look like this:

#include "MyClass1.h"
#include "MyFunc.h"
int main(int ac, char ** av)
{
    MyFunc a;
    MyClass1 b(a);
    b.setPtr(&MyFunc::MyDo);
    b.myDo();
}

Else, if your method can be static, add the "static" keyword to the method declaration (and take a pointer like this: "&MyFunc::MyDo").

Upvotes: 1

Related Questions