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!!
CodePudding user response:
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);
}
};