Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding function pointer - passing it as an argument

I want to pass a member function of class A to class B via a function pointer as argument. Please advise whether this road is leading somewhere and help me fill the pothole.

#include <iostream>


using namespace std;

class A{
public:

int dosomeA(int x){
    cout<< "doing some A to "<<x <<endl;
    return(0);
}
};

class B{
public:

B(int (*ptr)(int)){ptr(0);};
};

int main()
{
A a;
int (*APtr)(int)=&A::dosomeA;

B b(APtr);
return 0;
}

This brilliant piece of code leaves me with the compiler error:

cannot convert int (A::*)(int)' toint (*)(int)' in initialization

Firstly I want it to compile.
Secondly I don't want dosomeA to be STATIC.

like image 296
Stef Avatar asked Jan 22 '23 10:01

Stef


2 Answers

Pointers to members are different from normal function pointers. As the compiler error indicates the type of &A::dosomeA is actually int (A::*)(int) and not int (*)(int).

Inside B's constructor you need an instance of A to call the member on using one the .* or ->* operators.

E.g'

B(int(A::*ptr)(int))
{
    A atmp;
    (atmp.*ptr)(int);
}
like image 174
CB Bailey Avatar answered Mar 23 '23 22:03

CB Bailey


http://www.parashift.com/c++-faq-lite/pointers-to-members.html

You don't have a pointer to a function that returns an int and takes an int. You have a pointer to a member-function that returns an int and takes an A* and an int. Not only do you need to fix the type of your pointer, B needs to provide an A* to serve as dosomeA's this parameter.

Boost::bind has some functionality meant to simplify using function pointers in general, and they provide support for pointers to member functions. See here.

like image 38
Dennis Zickefoose Avatar answered Mar 24 '23 00:03

Dennis Zickefoose