Recently, I encountered one thing that I did not understand — pointers to functions of a class. Do they make sense? When are they used? Example:

class ABC { public: void show() { cout << "Hello" << endl; } }; int main() { void(ABC::*point)() = &ABC::show; // указатель на ф-цию класса ABC myClass; (myClass.*point)(); return 0; } 

Such pointers work only with the object. Isn't it more convenient to call class functions directly?

 ABC myClass; myClass.show(); 

Or

 ABC myClass; ABC * point2 = &myClass; point2->show(); 
  • Well, you might as well ask why you need pointers at all, if “it’s more convenient to refer directly to the specified entities”. - AnT
  • In Qt, signals and slots are implemented like this. - maestro

2 answers 2

When it is known in advance which function should be called, it is certainly easier to use an explicit call without any additional pointers. But this is not always the case. The problem can be viewed in the same sense as pointers to objects. Those. if we know which object to use, then we do not need a pointer variable to the object, and if such an object is not known in advance, then we need to use a pointer. The same with the function pointer. And by and large does not matter a member, or non-member. The presence of such pointers simply adds the necessary level of indirection to the program.

    Yes. We can add pointers to the map, or else somewhere and dynamically determine which function should be called. In this case, the method of calling will remain the same.

    http://ideone.com/zdYvce

     #include <iostream> using namespace std; class ABC { public: void f1() { cout << "#1" << endl; } void f2() { cout << "#2" << endl; } }; int main() { void (ABC::*f[])() = {&ABC::f1, &ABC::f2}; ABC myClass; int x; while(cin >> x) (myClass.*f[x&1])(); return 0; } 
    • Tell me please, what does [x & 1] mean? I understand that if x is even, then f1 is called, if it is odd, then f2 is called. - aleshka-batman
    • @ aleshka-batman yes. This is such an odd test. - αλεχολυτ