Search code examples
c++oopfunction-pointerspointer-to-member

How to pass function pointer to member function c++?


So this is like my 2nd question regarding the topic but this time I want to know what if i pass a function which is of int type.Like here I want to store output of fun1 in variable "int my" in main function. How should i write the wrapper function for this?

#include<iostream>
using namespace std;

class student
{
public:
    int fun1(int m) 
    { 
        return 2*m;
    }

    int wrapper(int (student::*fun)(int k))
    {
        (this->*fun)(int k)
    }
};

int main()
{   
    student s;
    int l=5;
    int my=s.wrapper(&student::fun1(l));
    cout << m << endl;
    return 0;
}

Solution

  • The wrapper caller needs two parameters:
    One for the function to call, and one for the parameter to call it with

    int wrapper(int (student::*fun)(int), int k)
    {
        return (this->*fun)(k);
    }
    

    Call it like:

    int my = s.wrapper(&student::fun1, 1);
    cout << my << endl;
    

    See it here http://coliru.stacked-crooked.com/a/cd93094c38bfa591