Function Pointers in C++

Function pointer, array of function pointers and passing function pointer as a parameter

#include <iostream>
using namespace std;

int foo()
{
    return 5;
}

int goo()
{
    return 6;
}

void fun_arr1(int x, int y) {
    cout << "x:" << x << " y:" << y << endl;
}

void fun_arr2(int x, int y) {
    cout << "x:" << x << " y:" << y << endl;
}

int fun_ptr_as_param(int (*fn)()) {
    return fn();
}

int main()
{
    int (*fcnPtr)() = foo;
    cout << "Calling function pointer. Value returned is:" << fcnPtr() << endl;
   
    fcnPtr = goo;
    cout << "Calling function pointer after re-assigning. Value returned is:" << fcnPtr() << endl;

    cout << "Passing function pointer as parameter. Value returned is:" << fun_ptr_as_param(fcnPtr) << endl;
   
    void (*funPtr[2])(int, int);
    funPtr[0] = fun_arr1;
    funPtr[1] = fun_arr2;
   
    cout << "Calling function pointer first item in array."
    funPtr[0](100, 200);
   
    cout << "Calling function pointer second item in array."
    funPtr[1](1000, 2000);
   
    return 0;
}


/********** OUTPUT **********
Calling function pointer. Value returned is:5
Calling function pointer after re-assigning. Value returned is:6
Passing function pointer as parameter. Value returned is:6
x:100 y:200
x:1000 y:2000

*/

Function pointer pointing to a class member function

#include <iostream>
using namespace std;
class cls_ptr {
    public:
        void fcn1(int val){
            cout << "Member function fcn1 called with value: " << val << endl;
        }
};

int main()
{
    void (cls_ptr::*mbr_fcn_ptr)(int);
    mbr_fcn_ptr = &cls_ptr::fcn1;
   
    cls_ptr obj; // NOTE creating an instance is needed.
    (obj.*mbr_fcn_ptr)(100);
   
    return 0;
}



Class field is a function pointer and it points to a member function.

#include <iostream>

using namespace std;

class cls_ptr {
    private:
       
void (cls_ptr::*fun_ptr)(int);

    public:
        cls_ptr() {
                this->fun_ptr = &cls_ptr::fcn1;
        }
       
        void fcn1(int val){
            cout << "Function pointer called with value: "
<< val << endl;
        }
       
        void call_fun_ptr(int val) {
            (this->*fun_ptr)(val);
        }
};

int main()
{
    cls_ptr obj;
    obj.call_fun_ptr(100);
   
    return 0;
}

No comments:

Post a Comment