Search code examples
c++member-pointers

Call function through pointer to class member


In following code:

class foo
{
public:
    void foo_function() {};
};

class bar
{
public:
    foo foo_member;

    void bar_function(foo bar::*p_foo)
    {
        // what is the corrct sintax for following:
        this->*p_foo->foo_function(); // expression must have a pointer type??
    }
};


int main()
{
    foo foo_obj;
    bar bar_obj;
    typedef foo bar::*p_foo;
    p_foo blah = &bar::foo_member;
    bar_obj.bar_function(blah);
    return 0;
}

What would be correct syntax to make bar::bar_function work?


Solution

  • This works in ideone:

    void bar_function(foo bar::*p_foo)
    {
        (this->*p_foo).foo_function();
    }
    

    It's all about having the right level of indirection. Since p_foo is a pointer to member, we need to dereference it before attempting to access it from this. At this point, you have the actual foo_member object, not a pointer to it, so you can call its foo_function by dot notation.