Calling member function that is being pointed.

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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'

Thanks in advance for any help
Last edited on
You've got bad syntax.
Change the last part of the class such as:
1
2
3
4
//...
public:
    void hello(){ cout << "hello" << endl;}
}myBar; //This make a global foo::myBar. 

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.

Like this:

1
2
3
    void other(Foo& foo){(foo.*(this->memberFunctionPointer))();}
...
testFoo.myBar.other(testFoo);


or this:

1
2
3
4
5
6
class bar
{
    foo* pfoo;
public:
    bar(foo* f):pfoo(f) {}
    void other(){(pfoo->*(this->memberFunctionPointer))();}


Remember: Only because bar is a member variable of foo doesn't mean it knows it's surrounding foo instance when you call to testFoo.myBar.*

Ciao, Imi.
Topic archived. No new replies allowed.