TheNVP TheNVP - 1 month ago 21
C++ Question

cannot convert 'int (B::*)(std::string)' to 'int (*)(std::string) ' in assignment pt2function=&B::generate_callback;

I am new to c++, .I am trying to create a pgm that contains 2 classes ,out of which one class has a member function that would generate a callback function in another class though a function pointer, but i keep getting the following error.

#include <iostream>
#include <string>

using namespace std;



class B
{
private: std::string str1;
public: int generate_callback(std::string str1);


};
int B::generate_callback(std::string str1)
{
if ((str1=="Generate")||(str1=="generate"))
{
Cout<<"Callback generated ";
}
return 0;
}

class A : public B
{
public:
void count(int a,int b);
private: int a,b;

};


void A::count(int a, int b)
{
for ( a=1;a<b;a++){
if(a==50)
{
cout<<"Generating callback ";

goto exit;

}
exit: ;
}
}

int (*pt2function)(string)=NULL;
int main()
{
B obj1;
A obj2;
string str;
cout<<"To generate callback at int i=50 please enter 'generate'";
cin>>str;
obj2.count(1,100);
pt2function=&B::generate_callback;
(obj1.*pt2function)(str);
return 0;
}


The errors :

main.cpp:57: error: cannot convert 'int (B::*)(std::string) {aka int (B::*)(std::basic_string<char>)}' to 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}' in assignment
pt2function=&B::generate_callback;

/home/adt/practice/N_practise/n_pract_2/pract2/main.cpp:58: error: 'pt2function' cannot be used as a member pointer, since it is of type 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}'
(obj1.*pt2function)(str);
^
^

Answer

The variable pt2function is a pointer to a non-member function. Such a pointer is not compatible with a pointer to a member-function. Which is what the compiler tells you with the first error: A int (*)(string) is not compatible with a int (B::*)(string).

You need to define pt2function as a pointer to a B member function:

int (B::*pt2function)(string)=NULL;

Now you can initialize or assign a matching member function of B to the variable pt2function.

This also solves the second errors, which basically says that in your current code the variable pt2function is not a pointer to a member function, and therefore can not be used as such.