bMathew
bMathew

Reputation: 103

Calling Member function pointers from vector list

I'm new to function pointers and I wrote a small program, where main class use Test class to populate a list with member function pointers. And from my main class I want to call ExeFuns() to call each member function, which I'm not sure how to do. Any help is greatly appreciated. Thanks.

Test.h

Class Test{
  public : 
   void CallFun1(); 
   void CallFun2();

   void AddFuns(); 
   void ExeFuns();      
}; 

Test.cpp

std::vector<void (Test::*) ()> callist; 


void Test::AddFuns(){
  callist.push_back(&Test::CallFun1); 
  callist.push_back(&Test::CallFun2); 
}


void Test::ExeFuns(){
  for (int i = 0 ; i<eventlist.size(); i++)
  {
   callist[i](); // error!
  }
}

void Test::CallFun1(){ cout<<"Fun 1"<<endl; }
void Test::CallFun2(){ cout<<"Fun 2"<<endl; }

Main.cpp

main()
{
Test obj; 
obj.AddFuns(); 
obj.ExeFuns(); 
}

Upvotes: 2

Views: 6051

Answers (2)

Arun
Arun

Reputation: 2092

In short, you need .* or -> operators to invoke member methods. Also, there are several compilation errors and one out of bounds access in your code. Here is the correct approach,

void Test::ExeFuns(){
  for (int i = 0 ; i<callist.size(); i++) // also there is out of bounds access (usage of <=) in your code
  {
    (this->*callist[i])(); // or (*this.*callist[i])();
  }
}

Upvotes: 2

Torp
Torp

Reputation: 7924

Those are not pointers to standalone functions, they are pointers to member functions of a class. As chris said, you need an object to call them on.

Check this SO question.

Upvotes: 0

Related Questions