- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function pointer to member function in C++
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
#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
Advertisements