Search code examples
c++pointer-to-member

Function pointer to memberfunction of other instace


class A
{
private:
    int _i;

    int calc() { return i; }

public:
    int (*get)() = &A::calc;

    A(int i){ _i = i; }
    A(A *a ) { get = a->get; }
};

int main(){
    A a = new A(5);
    A b = new A(a)
}

Hi, I think I have a kind of special question. I dont know the right tag, so I try to descripe best possible:

There is a class A with a function calc and a function pointer get with equal footprint of calc. Typically get should be refer to calc of its own instance but for special condition it should be redirected to calc of an other instance. Is there a way to implement it?

Thank you. (syntax is pseudocode)

edit: Background is that calc does some complex calculations with a lot of different member variables and I only want to get the result


Solution

  • sure:

    std::function<int()> get = std::bind(&A::calc, this);
    

    later, you can change it to point to the other instance "b":

    get = std::bind(&A::calc, &b)
    

    Also note that your code would not compile as you are attempting to assign a member function pointer (&A::calc) to a plain function pointer (int(*)()). The syntax for declaring member function pointer would be int(A::*get)(), but then you would only be able to invoke that member function pointer if you have an instance on your hand (unless you bind it like in the solution I provided above).

    instance.*get();
    
    or
    
    pointer ->* get();
    

    Note the use of .* and ->* operators