Function pointer to member function in C++

C++Server Side ProgrammingProgramming

In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe.

Example

 Live Demo

#include <iostream>
using namespace std;
class AB {
   public:
      int sub(int a, int b) {
         return a-b;
      }
      int div(int a, int b) {
         return a/b;
      }
};
//using function pointer
int res1(int m, int n, AB* obj, int(AB::*fp)(int,int)) {
   return (obj->*fp)(m,n);
}
//using function pointer
int res2(int m, int n, AB* obj, int(AB::*fp2)(int,int)) {
   return (obj->*fp2)(m,n);
}
int main() {
   AB ob;
   cout << "Subtraction is = " << res1(8,5, &ob, &AB::sub) << endl;
   cout << "Division is = " << res2(4,2, &ob, &AB::div) << endl;
   return 0;
}

Output

Subtraction is = 3
Division is = 2
raja
Updated on 30-Jul-2019 22:30:26

Advertisements