0

I am creating an instance of class B in a method of class A (which is a QMainWindow) with B instanceB; and then call a method of B with B.method() and pass it the function pointer of a method of A.

Now the compiler says argument of type "void (A::*)()" is incompatible with parameter of type "void (*)()". How do I resolve this if possible?

Code:

void A::method1_of_A(void)
{
    B instanceB;
    B.methodB(method2_of_A); // this is where the compiler complains
}
RadaD
  • 85
  • 7
  • If you wrote a function that accepts a `void (*)()` argument, you should rewrite it. If somebody else wrote it, complain to them loudly. Such function is *unusable*. It should accept a `std::function` argument instead. – n. m. could be an AI Mar 31 '23 at 09:16
  • I wrote it myself. So `methodB` should be `void B::methodB(std::function)` instead of `void B::methodB(void (*function)())`? Because that's what I took from a "function pointers in C++" article. Can you elaborate on the difference? – RadaD Mar 31 '23 at 09:25
  • Generally, can you point me to the right source to learn about all this? – RadaD Mar 31 '23 at 09:37
  • Which article is that? `void (*)()` can *only* access global variables. It is fundamentally incompatible with any member function pointer that has an implicit `this` parameter. – n. m. could be an AI Mar 31 '23 at 09:52
  • 1
    @RadaD Your basic mistake is that `method2_of_A` is not a function, it's a method. One solution is to change `methodB` to accept a pointer to a method, e.g. `void methodB(void (A::*function)())` Without knowing the context this may not be correct for you. But that's the basic mistake, methods cannot be assigned to function pointers. – john Mar 31 '23 at 10:02

1 Answers1

2

Parameter void (*)() can only accept a free function.

If you have parameter std::function<void()>, it can call any callable, so you can adapt your member function with a lambda capturing the object and pass that

B.methodB([&a](){ a.method2_of_A(); })

or binding the member function to the object (including <functional>)

B.methodB(std::bind(&A::method2_of_A, a))

Of course, clearest intent is in @John's comment, where you know a member function of A is expected:

void methodB(void (A::*function)()) { (this->*function)(); }
stefaanv
  • 14,072
  • 2
  • 31
  • 53