Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a member function pointer

Tags:

c++

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;
}
like image 599
Roshan Mehta Avatar asked Dec 13 '22 10:12

Roshan Mehta


1 Answers

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
like image 113
lubgr Avatar answered Dec 16 '22 00:12

lubgr