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 
        }
}
8
  • Also see: stackoverflow.com/questions/30573184/… Commented May 6, 2020 at 19:12
  • @NathanOliver: Updated with proper syntax for declaring vector of function pointers but I'm facing issues while calling the function pointer using the syntax: (I've updated in the code. this->*fp_list.at(0)(100); Commented May 6, 2020 at 19:43
  • I believe you need another set of parentheses: this->*(fp_list.at(0))(100); Commented May 6, 2020 at 19:45
  • Tried this too actually but same error & cribbing for "error: must use '.' or '->' to call pointer-to-member function in" Commented May 6, 2020 at 19:48
  • 2
    Aha, try (this->*fp_list.at(0))(100). Commented May 6, 2020 at 19:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.