Reputation: 3810
I've a scenario as below code. I'm trying to
Store the address of a C++ member function in a vector of function pointers.
access a C++ member function using this vector of function pointers.
I am able to add the functions, but I can't call them. The error I get is:
error: must use '.' or '->' to call pointer-to-member function in
class allFuncs {
private:
std::vector<void *(allFuncs::*)(int)> fp_list; // Vector of function pointers
void func_1(int a) {
// some code
}
void func_2(int a) {
// some code
}
void func_3() {
// STORING THE FUNCTION POINTER INTO The VECTOR OF FUNCTION POINTERS
fp_list.push_back(&func_2);
fp_list.push_back(allFuncs::func_1);
}
func_4() {
// Calling the function through the function pointer in vector
this->*fp_list.at(0)(100); // this does not work
}
}
Upvotes: 2
Views: 532
Reputation: 180630
You need to use
(this->*fp_list.at(0))(100)
to call the function from the vector. When you do
this->*fp_list.at(0)(100)
The function call (the (100)
part) is bound to fp_list.at(0)
so basically you have
this->*(fp_list.at(0)(100))
which won't work. Adding parentheses around the function pointer access fixes that so this->*fp_list.at(0)
becomes the function to call and then the (100)
is used on that function.
Upvotes: 1