Yonghui
Yonghui

Reputation: 222

C++ How to pass member function pointer to another class?

Here is what I want to realize:

class Delegate
{
public:
    void SetFunction(void(*fun)());
private:
    void(*mEventFunction)();
}

Then is the class named Test

class Test
{
public:
    Test();
    void OnEventStarted();
}

Now in Test(), I want to pass OnEventStarted to Delegate like this:

Test::Test()
{
    Delegate* testClass = new Delegate();
    testClass->SetFunction(this::OnEventStarted);
}

But OnEventStarted is a non-static member function, how should I do?

Upvotes: 4

Views: 4426

Answers (2)

SergeyA
SergeyA

Reputation: 62553

In order to call a member function, you need both pointer to member function and the object. However, given that member function type actually includes the class containting the function (in your example, it would be void (Test:: *mEventFunction)(); and would work with Test members only, the better solution is to use std::function. This is how it would look like:

class Delegate {
public:
    void SetFunction(std::function<void ()> fn) { mEventFunction = fn);
private:
    std::function<void ()> fn;
}

Test::Test() {
    Delegate testClass; // No need for dynamic allocation
    testClass->SetFunction(std::bind(&Test::OnEventStarted, this));
}

Upvotes: 6

Eric Hegedus
Eric Hegedus

Reputation: 23

You should pass &Test::OnEventStarted, this is the right syntax for a member function pointer

And after that, you'll have to get an instance of the Test class to run the function like this

instanceOfTest->*mEventFunction()

Upvotes: 0

Related Questions