Search code examples
c++functionpointersunreal-engine4

How to convert void (myClass::*)() to void (*)()


I'm currently working on a C++ project on the Unreal Engine and I can't wrap my head around this problem.

class A
{
public: 
    void (* array[10])();

    //Add Function to an array
    void AddFunctionToArray(void(*function)());
};

class B
{
public: 

    A a;

    //Sending a B function to A
    void SendMyFunction();
    void Foo();
};

void B::SendMyFunction()
{
   a.AddFunctionToArray(&B::Foo);
}

I get the error: can't convert void (B::*)() to void (*)()

How can I send a function pointer from one of my class to another?


Solution

  • void (B::*)() is a pointer to a non-static member function, while void (*)() is a pointer to a non-member function. There is no conversion between the two.

    Making B::Foo static would fix this problem. However, you will have no access to instance members of B.

    Note that using function pointers, member or non-member, is an old style of passing function objects. A more modern way is using std::function objects, which can be constructed from a combination of an object and one of its member functions.