Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass class method as an argument to another class method

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!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
      }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading