2
votes

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(); 
}
2
You need an object to call them on.chris
If you have a C++11 compatible compiler (almost all are today), then you might want to look into std::function and std::bind. If you don't have C++11, then Boost.Function and Boost.Bind do the same.Some programmer dude
Oh, and you have a off-by-one error in your ExeFuns loop.Some programmer dude

2 Answers

1
votes

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])();
  }
}
0
votes

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.