Alireza
Alireza

Reputation: 13

Passing a member function as arguments using pointer-to-member-function C++

I am trying to pass a member function as argument using pointer-to-member-function. I have already seen some links like this here but I could not solve the problem.

The class Foo has two member functions. I need to pass the addition function as an argument to the NewOper function. This is my code. I can correctly use pointer to call the addition function but it gives me an error when I try to pass it as an argument to NewOper function. I appreciate it if you tell me how I can fix it. (The last two lines cause error)

#include <iostream>
using namespace std;
class Foo{
public:
    int addition(int a, int b)
    {
        return (a + b);
    }

    int NewOper(int x, int y, int(*fnc2call)(int, int))
    {
        int r;
        r = (*fnc2call)(x, y);
        return (r);
    }
};
int main()
{
    int m,n, k, l;
    int (Foo::*fptr) (int, int) = &Foo::addition;
    Foo obj;
    m=(obj.*fptr)(1,2);
    Foo* p = &obj;
    n=(p->*fptr)(3,4);
    cout << m << endl;
    cout << n << endl;
    //**********************
    int (Foo::*fptr) (int, int, int(*fnc2call)) = &Foo::NewOper;
    k = (obj.*fptr)(1, 2, addition);
}

Upvotes: 1

Views: 76

Answers (1)

mvidelgauz
mvidelgauz

Reputation: 2214

You already have answer in your own code:

int (Foo::*fptr) (int, int) = &Foo::addition - here you correctly declared fptr as pointer to function, which is (non static) member of class Foo

But you forgot to do the same in you NewOper function definition:

int NewOper(int x, int y, int(*fnc2call)(int, int)) - this function wants address of free function as 3rd argument. Redefine it in the same way you declared fptr. But then you'll need to pass also pointer to an object of class Foo to this function

Alternatively, you can make your function addition function static as Jarod42 suggested (actually, the way it is written now, there is no reason for it to be member of class Foo unless you have further plan on it). Then you'll need to remove Foo:: from fptr definition

Upvotes: 1

Related Questions