2

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(); 
}
bMathew
  • 103
  • 1
  • 13
  • 2
    You need an object to call them on. – chris Oct 04 '13 at 05:32
  • If you have a C++11 compatible compiler (almost all are today), then you might want to look into [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind). If you don't have C++11, then [Boost.Function](http://www.boost.org/doc/libs/1_54_0/doc/html/function.html) and [Boost.Bind](http://www.boost.org/doc/libs/1_54_0/libs/bind/bind.html) do the same. – Some programmer dude Oct 04 '13 at 05:35
  • 1
    Oh, and you have a off-by-one error in your `ExeFuns` loop. – Some programmer dude Oct 04 '13 at 05:37

2 Answers2

1

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])();
  }
}
Arun
  • 2,087
  • 2
  • 20
  • 33
  • Thanks for your comments. How would I get the same result if I use vector::pop_back()? – bMathew Oct 04 '13 at 05:57
  • 1
    pop_back doesn't return any value, hence you can't use it to invoke the method, but you can still use vector::back() as (this->*callist.back())(); – Arun Oct 04 '13 at 06:23
0

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.

Community
  • 1
  • 1
Torp
  • 7,924
  • 1
  • 20
  • 18