2

I have two class:

typedef int(*sumpointer)(int a, int b);

class A 
{
    A(sumpointer a, int b, int c)
    {
        // DO SOMETHING
    }
};

class B {
    A *a;
    B()
    {
        a = new A(sum, 5, 6);
    }
    int sum(int a, int b) {
        return (a + b);
    }
};

On line a = new A(sum, 5, 6); I have a syntax error:

No instance of constructor "A::A" matches the argument list argument
types are (int(int a, int b), int , int)

How can I fix it?

4
  • I member function cannot be used like this. Let me find a duplicate on SO. Commented Jul 30, 2018 at 3:36
  • That's not a syntax error. Commented Jul 30, 2018 at 3:37
  • 2
    There are many posts related to this subject if you search for "using member function pointer in callback". I couldn't find one that I could mark as a duplicate in good conscience. stackoverflow.com/…. Commented Jul 30, 2018 at 3:46
  • Actually, i have to convert a DLL from C# to C++. In C# they using delegate, "sum" is private method of B, and it work. In C++, i try to use function pointer but i got wrong. Commented Jul 30, 2018 at 3:48

2 Answers 2

3

You cannot use a raw function pointer to point at a non-static class method. You need to use a pointer-to-member instead, eg:

class A;

class B {
    A *a;
    B();
    int sum(int val1, int val2);
};

typedef int (B::*sumpointer)(int val1, int val2);

class A {
    A(B *b, sumpointer s, int val1, int val2);
};

A::A(B *b, sumpointer s, int val1, int val2)
{
    (b->*s)(val1, val2);
}

B::B() {
    a = new A(this, &B::sum, 5, 6);
}

int B::sum(int val1, int val2) {
    return (val1 + val2);
}

In C++11 and later, use std::function instead:

#include <functional>

using sumpointer = std::function<int(int, int)>;

class A {
    A(sumpointer s, int val1, int val2);
};

class B {
    A *a;
    B();
    int sum(int val1, int val2);
};

A::A(sumpointer s, int val1, int val2)
{
    s(val1, val2);
}

B::B() {
    a = new A([this](int val1, int val2) { return this->sum(val1, val2); }, 5, 6);
    /* or:
    using std::placeholders::_1;
    using std::placeholders::_2;
    a = new A(std::bind(&B::sum, this, _1, _2), 5, 6);
    */
}

int B::sum(int val1, int val2) {
    return (val1 + val2);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank a lot. I will try it.
1

The easiest fix is to move sum out of B:

int sum(int a, int b) {
    return (a + b);
}

class B {
    A *a;
    B()
    {
        a = new A(sum, 5, 6);
    }    
};

2 Comments

Actually, this is my simplest example for my code. "Sum" have to be a method of B, so i can't move it out.
@NguyễnVũHiếuHọc I'm answering the question you asked. If you have other code with a different problem, post the other code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.