0

I'm learning C++, and I was wondering how to pass class method as an argument to another class method. Here's what I have now:

class SomeClass {
   private:
      // ...
   
   public:
      AnotherClass passed_func() {
          // do something
          return another_class_obj;
      }
      
      AnotherClassAgain some_func(AnotherClass *(func)()) {
          // do something
          return another_class_again_obj;
      }
      
      void here_comes_another_func() {
          some_func(&SomeClass::passed_func);
      }
};

However, this code gives error:

cannot initialize a parameter of type 'AnotherClass *(*)()' with an rvalue of type 'AnotherClass (SomeClass::*)()': different return type ('AnotherClass *' vs 'AnotherClass')

Thanks!!

1 Answers1

1

The type of a member function pointer to SomeClass::passed_func is AnotherClass (SomeClass::*)(). It is not a pointer to a free function. Member function pointers need an object to be called, and special syntax (->*) :

struct AnotherClass{};
struct AnotherClassAgain{};

class SomeClass {
   private:
      // ...
   
   public:
      AnotherClass passed_func() {
          // do something
          return {};
      }
      
      AnotherClassAgain some_func(AnotherClass (SomeClass::*func)()) {
          (this->*func)();
          // do something
          return {};
      }
      
      void here_comes_another_func() {
          some_func(&SomeClass::passed_func);
      }
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • I got `error: expected expression` where it does `(this->*func)();`. –  Dec 10 '21 at 16:26
  • @bichanna compiles fine here: https://godbolt.org/z/TKa9PPW6G. Maybe you made a typo somewhere – 463035818_is_not_an_ai Dec 10 '21 at 16:29
  • I'm using g++, but I think you are using gcc. Could you please convert it so g++ can compile? –  Dec 10 '21 at 16:30
  • basically g++ is gcc (https://stackoverflow.com/questions/172587/what-is-the-difference-between-g-and-gcc). Can you show the code you tried to compile? If it is an exact copy paste of the code in my answer then something else is wrong – 463035818_is_not_an_ai Dec 10 '21 at 16:32
  • Oh, nvm. I got it. I tried to compile another file. –  Dec 10 '21 at 16:32