2

Possible Duplicate:
How to best pass methods into methods of the same class

I've never had problems passing a function pointer as parameter. This works:

void functionThatTakesFPTR(void(*function)(int), int someValue){ 
    function(someValue);
   }

void printValue(int value){
    std::printf("%d",value);
}

int main(int argc, char** argv){
    functionThatTakesFPTR(&printValue, 8);

    return EXIT_SUCCESS;
}

However, passing object function doesn't

void MyClass::setter(float value){ }

void MyClass::testFunction(void(*setterPtr)(float)){ }

void MyClass::someFunc(){
     testFunction(&(this->setter));
}

To me this looks like passing the address of this instead of the function, and I'm a bit confused. Is it possible to do so? And is it possible to pass the function pointer of object of another class (of instance MyClass2) ?

Edit: Error I'm getting is "class 'MyClass' has no member 'setter' ".

Community
  • 1
  • 1
Mercurial
  • 2,095
  • 4
  • 19
  • 33

1 Answers1

8

The problem is that a call to a method also requires a reference to the class instance. You can't simply call a class method like a stand-alone function.

You need to read about Pointer-to-Member Functions.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466