c++pointer-to-membermember-pointers

C++: Is it posible to asign a method to a function-pointer-member (atribute) in the same class?


That's what I'm trying to do: I have a class whit a member (attribute) which is a function pointer. In the creator I want to assign some methods of the same class to that pointer (depending of some condition) and use it after in other methods. For example:

class monton
 {
 private:
 protected:
  
  bool (*comparador)(int a, int b);

  inline bool mayor(int a, int b) {return a > b;}
  inline bool menor(int a, int b) {return a < b;}
  ...

 public:
  monton (bool maximo = true)
   {
   if(maximo) comparador = mayor;
   else       comparador = menor;
   }
  ...
 };

When I compile this code in CodeBlocks, I get this error:

error: cannot convert ‘monton::mayor’ from type ‘bool (monton::)(int, int)’ to type ‘bool (*)(int, int)’|

Solution

  • This error tells you that you are trying to assign a pointer to non-static member function to a variable of regular function pointer type. correct pointer declaration would be:

    bool (monton::*comparador)(int a, int b);
    // or even better with type alias
    using t_ComparadorPointer = bool (monton::*)(int a, int b);
    t_ComparadorPointer comparador;