1

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 :(

2

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Teller what if fun1 return some int, then how should i write wrapper? I am storing the return of fun1 say in some variable x in main.
@codie - Then you modify the code to have some return statements, as you would with regular function pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.