
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Calling a member function on a NULL object pointer in C++
- Function Pointer in C
- How to declare member function in C# interface?
- Declare a C/C++ function returning pointer to array of integer function pointers
- How to declare a pointer to a function in C?
- How to assign a pointer to function using C program?
- Count the number of objects using Static member function in C++
- Count the number of objects using Static member function in C++ Program
- Golang Pointer to an Array as Function Argument
- Golang program to implement returning pointer from a function
- Double Pointer (Pointer to Pointer) in C
- Function that takes an interface type as value and pointer in Golang
- How to define pointer to pointer in C language?
- Passing Arrays to Function in C++
- iswblank() function in C/C++

Advertisements