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

Passing a function pointer to a member function in C++.Getting error


Hi it is my first experience with passing function pointer in C++. So here is my code:-

#include <iostream>
using namespace std;

// Two simple functions
class student
{
public:
void fun1() { printf("Fun1\n"); }
void fun2() { printf("Fun2\n"); }

// A function that receives a simple function
// as parameter and calls the function
void wrapper(void (*fun)())
{
    fun();
}
};

int main()
{   student s;

    s.wrapper(s.fun1());
    s.wrapper(s.fun2());
    return 0;
}

Initially in wrapper function i passed only fun1 and fun2.I got an error

try.cpp:22:15: error: ‘fun1’ was not declared in this scope
     s.wrapper(fun1);
               ^~~~
try.cpp:23:15: error: ‘fun2’ was not declared in this scope
     s.wrapper(fun2);

Later I tried to pass s.fun1() and s.fun2() as argument but again got error

try.cpp:23:23: error: invalid use of void expression
     s.wrapper(s.fun1());
                       ^
try.cpp:24:23: error: invalid use of void expression
     s.wrapper(s.fun2());

Please help I don't know what to do :(


Solution

  • Let's deal with the two issues in the post.

    1. You are calling fun1 and fun2. Since their return type is void, you can't pass their result as something's value. In particular as the value of a function pointer. You also can't obtain their address by using the dot member access operator. Which brings us to the following.

    2. Member functions are not like regular functions. You cannot just take their address. Their treatment is special, because member functions can only be called on an object. So there's a special syntax for them, which involves the class they belong to.

    Here's how you would do something like what you are after:

    class student
    {
    public:
        void fun1() { printf("Fun1\n"); }
        void fun2() { printf("Fun2\n"); }
    
        // A function that receives a member function
        // as parameter and calls the function
        void wrapper(void (student::*fun)())
        {
            (this->*fun)();
        }
    };
    
    int main()
    {   student s;
    
        s.wrapper(&student::fun1);
        s.wrapper(&student::fun2);
        return 0;
    }