0

Consider the code snippet below for a second:

class A{
public:
  void shout(int, void (*callback)(int)){}
  void doubleValue(int){}

  void call_shout(){
    shout(2, (*doubleValue)(int));
  }
};

How to call the shout function with the doubleValue function as a parameter inside the call_shout function?

VytautasK
  • 77
  • 1
  • 6
  • 1
    Just as you call any other function: `callback(1012);` – the pointer is de-referenced implicitly just as taking the address of is, though you could be explicit about as well: `(*callback)(1210);`, just as you could when taking the address (`&someFunction`). – Aconcagua May 11 '22 at 09:31
  • 1
    Pointers to class methods have the prototype `(ClassName::(*variableName)(parameters))`. Calling them is done by using the object reference, like `(this->*name)(value)`. An example can be found @ https://newbedev.com/calling-c-class-methods-via-a-function-pointer – Refugnic Eternium May 11 '22 at 09:32
  • 2
    @RefugnicEternium Correct syntax for member function pointers is `void (A::*callback)(int)`, especially you need to include the return type (`ReturnType (ClassName::*variableName)(Parameters)`). – Aconcagua May 11 '22 at 09:35
  • 2
    what is `print` ? Please read about [mcve]. Though anyhow there are duplicates... trying to find one – 463035818_is_not_a_number May 11 '22 at 09:38
  • 1
    the top answer is the duplicate is quite elaborate. It also contains a section on member function pointers – 463035818_is_not_a_number May 11 '22 at 09:40
  • 1
    @RefugnicEternium About wording: C++ standard doesn't know about *'methods'*, all it knows about is *'member functions'*. As you obviously mean the same you shouldn't introduce duplicate terminology. Use it where the language's standard does, e.g. Java. – Aconcagua May 11 '22 at 09:44
  • 1
    You are correct, my bad. My point however was, that their `shout` function takes a pointer to a global function. In order to call the `doubleValue` member function, they will require a 'Pointer to member function' (`void (A::*memberFunction)int)` in the concrete example. Which would then need to be called with `(this->*memberFunction)(value)`. – Refugnic Eternium May 11 '22 at 09:46

0 Answers0