#include <iostream>
using std::cout;
using std::endl;
class foo;
class bar
{
public:
void (foo::*memberFunctionPointer)();
void other(){((this)->*(this->memberFunctionPointer))();} //Error
};
class foo
{
public:
bar myBar;
void hello(){ cout << "hello" << endl;}
};
int main()
{
foo testFoo;
testFoo.myBar.memberFunctionPointer = &foo::hello;
((testFoo).*(testFoo.myBar.memberFunctionPointer))(); //OK
testFoo.myBar.other();
return 0;
}
Unfortunately, compiler stops at ((this)->*(this->memberFunctionPointer))();
with error: pointer to member type 'void (foo::)()' incompatible with object type 'bar'
Well, the problem is exactly what it's saying. You are trying to call a member function of class foo with a this-pointer of class bar.
((this)->*(this->memberFunctionPointer))();
The second this-> is redundant, since you are in the scope of bar, so lets write this as
((this)->*(memberFunctionPointer))();
you see? "this" is of type bar* here, whereas memberFunctionPointer is of type "void foo::*()", hence the error. If you want to call a member function of class foo within bar, then you either have to pass a foo* - parameter to other() or store such an object within bar.