2

I've a scenario as below code. I'm trying to

  1. Store the address of a C++ member function in a vector of function pointers.

  2. 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 
        }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
codeLover
  • 3,720
  • 10
  • 65
  • 121

1 Answers1

1

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.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
NathanOliver
  • 171,901
  • 28
  • 288
  • 402