Kumar Roshan Mehta
Kumar Roshan Mehta

Reputation: 3306

Call a member function pointer

How to call a member function pointer which is assigned to a member function? I am learning callbacks and this is just for learning purpose. How I can invoke m_ptr function ?

class Test{
   public:
       void (Test::*m_ptr)(void) = nullptr;
       void foo()
       {
           std::cout << "Hello foo" << std::endl;
        }

   };

void (Test::*f_ptr)(void) = nullptr;

int main()
{
     Test t;
     f_ptr = &Test::foo;
     (t.*f_ptr)();     
     t.m_ptr =  &Test::foo;
    //  t.Test::m_ptr();   //Does not work
    //  t.m_ptr();         //Does not work
    //  (t.*m_ptr)();      //Does not work
     return 0;
}

Upvotes: 4

Views: 111

Answers (3)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

Operator .* requires expression that return a pointer to member of class-type on the right side and expression which object of that type on the left side (i.e. t in your case). But your pointer is a member, so right expression should be t.m_ptr

Upvotes: 1

Caleth
Caleth

Reputation: 62694

If you have C++ 17, you can also

std::invoke(t.m_ptr, t);

Upvotes: 4

lubgr
lubgr

Reputation: 38267

You are almost there. Recall that m_ptr is a data member itself, so in order to access it you need to tell the compiler to resolve that relationship to the instance holding the pointer to member. Call it like this:

 (t.*t.m_ptr)();
 //  ^^ this was missing

Upvotes: 7

Related Questions