-1

I have a class which has a data memeber which store a member function pointer. The pointer points to different member functions in different time. I would like to call this funcion pointer from another member function. How can i do this?

class A {

  void (A::*fnPointer)() = nullptr;

  void callerMemberFunction(){
    fnPointer = &A::someMemberFunction;  // Store the function
    (*fnPointer)(); // I would like to call the function. How can i do?
  }

  void someMemberFunction(){ ... }

}

   
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    `(*this.*fnPointer)();` – 김선달 Jun 02 '21 at 10:30
  • I know this doesn't answer the question because you are specifically asking about a function pointer, nevertheless a more modern approach would be to use `std::function fn;` as the member variable, then assign a lambda to it: `fn = [this](){someMemberFunction();};` and call it simply using `fn()`. `std::function` is part of the STL and can be included using `#include `. – David Wright Jun 02 '21 at 10:45
  • @DavidWright -- in many cases, `std::function` adds overhead with no corresponding benefit. `std::function` is designed to manage impedance mismatches, for example, providing an interface that can be called with an argument of type `long`, and applying an underlying function that takes `int` or `double` or anything else that `long` can be converted to. If you don't need that kind of conversion, you don't need `std::function`. – Pete Becker Jun 02 '21 at 13:56

1 Answers1

3

You need to specify which object to call the function on:

(this->*fnPointer)();
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214