Question

I have a class (B) which has a static member pointer to an object of another class (A). In one member function of the first class (B), I need a function pointer that points to a member function of the second class (A).

class A
{
public:
    int DoubleValue(int nValue)
    {
        return nValue * 2;
    }
};

class B
{
private:
    static A* s_pcA;
public:
    void Something()
    {
        // Here a need the function pointer to s_pcA->DoubleValue()
    }
};

I have tried this:

int (*fpDoubleValue) (int nValue) = s_pcA->DoubleValue;

But Xcode says "Reference to non-static member function must be called".

Was it helpful?

Solution

You cannot obtain pointer to a member function of a class instance. Instead, you need to create a function object that contains pointer to a class instance and to a member function. You can use std::bind for that purpose:

auto fpDoubleValue = std::bind (&A::DoubleValue, s_pcA , std::placeholders::_1);

OTHER TIPS

Lambda function also can be used:

auto fpDoubleValue = [](int nValue) { return s_pcA->DoubleValue(nValue); };

You may use a pointer on method:

int (A::*fpDoubleValue) (int nValue) = &A::DoubleValue;

or in your case make the method static since it doesn't depend of this:

class A
{
public:
    static int DoubleValue(int nValue) { return nValue * 2; }
};

then

int (*fpDoubleValue) (int nValue) = &A::DoubleValue;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top