Function pointer in a C++ class

Asked

Viewed 3,755 times

4

I’m having trouble putting a pointer to a function in a class:

int Menu::validaescolha(){
    cout << 1232;
    return 1;
}
int Menu::inicial(){
    int (Menu::*funcs)() = &Menu::validaescolha;
    funcs();
    return 0;
}

Return these errors:

1 - Error (active) E0109 expressions preceding apparent call parentheses must have function type (pointer-to-)

2 - Error C2064 the term cannot be evaluated as a function receiving 0 arguments

I have no idea what to do here...

  • In C++ it is usually used functors or better yet Amble in newer versions (already 6 years). Pointer to function is C thing. And there are several errors there.

  • Can you give me an example of what this would look like using what you said?

  • D take a look at this: http://en.cppreference.com/w/cpp/language/lambda

1 answer

4


Pointer to method is a technique not widely used (I think), and so few people know. I had to do some research to find out that you need to use additional parentheses when using the pointer. Note that it is necessary to have an object to call the method through the pointer.

This applies to nonstatic methods. Pointers for static methods are not special, they are declared in the same way as pointers for "common" functions (which are not members of a class).

#include <iostream>
using namespace std;

class Menu
{
   public:
      int validaEscolha();
      static int stValidaEscolha();
      int inicial();
};


int Menu::validaEscolha()
{
   cout << 1232 << endl;
   return 1;
}

int Menu::stValidaEscolha()
{
   cout << 1232 << endl;
   return 1;
}

int Menu::inicial()
{
   // ponteiro para método não estático
   int (Menu::*funcs)() = &Menu::validaEscolha;
   (this->*funcs)();

   // ponteiro para método estático
   int (*stFuncs)() = &Menu::stValidaEscolha;
   stFuncs();

   return 0;
}

int main()
{
   Menu m;
   m.inicial();
}
  • Good. Complementing: Pointers for methods have special treatment because the offset has to be calculated within the class. Static functions do not depend on any instance of the class, so they are like free functions.

  • Just what I needed, thank you very much @José X.

  • mark the answer as accepted, please

Browser other questions tagged

You are not signed in. Login or sign up in order to post.