-1

I have some 3rd-part code:

class A(){
    public:
        void assingOnClickFunction(void (*function)(); 
};

I cannot change anything in that code. I want to pass to that A::assingOnClickFunction() my method of class B, void B::someFunction(). I have tried (all inside of the B class!):

a->assingOnClickFunction(this->someFunction);

But I get the error:

function call missing argument list; use '&B::someFunction' to create a pointer to member

So I have changed it to:

a->assingOnClickFunction(&B::someFunction);

But now there is ofc the error about the different types: (void(*)() and (&B::*)()

I cannot make B::someFunction() static (it uses a lot of non-static B's members and methods)!

So, is there an option to pass my B::someFunction() to the A::assingOnClickFunction(), not changing it to static and not changing anything in A class (A is not and cannot be aware of B, B includes A)?

PolGraphic
  • 3,233
  • 11
  • 51
  • 108

3 Answers3

3

If the member function you want to pass is not static, you cannot do that. The method in A accepts a function pointer to a function with no arguments, and a non-static member function has an implicit this pointer argument.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
2

In order to call a (non-static) method of an object, you need to know both the object and the method to call.

The assingOnClickFunction() function only takes a pointer to a function, so you cannot pass it the needed information.

Besides some horrible hacks, like implementing a function that has access to some global instance of your object, and calls the method throught that, it can't be done.

Peter Allin
  • 81
  • 1
  • 2
  • Indeed, I was thinking about something like that 'hacks'. But I guess I should rebuild my code and make it in some other way (it would looks really horrible with global instances and functions with access to it). – PolGraphic Feb 05 '13 at 20:30
1

A pointer to member function is not a pointer to function. If you have a function that takes an argument whose type is pointer-to-function, you cannot call it with a pointer to member function.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165