Wednesday, March 3, 2010

Programmer - Passing member function pointer to member object in c++

Programmer Question

I have a problem with using a pointer to function in C++. Here is my example:



#include <iostream>

using namespace std;

class bar
{
public:
void (*funcP)();
};

class foo
{
public:
bar myBar;
void hello(){cout << "hello" << endl;};
};

void byebye()
{
cout << "bye" << endl;
}


int main()
{
foo testFoo;

testFoo.myBar.funcP = &byebye; //OK
testFoo.myBar.funcP = &testFoo.hello; //ERROR
return 0;
}


Compilator returns an error at testFoo.myBar.funcP = &testFoo.hello;:




ISO C++ forbids taking the address of a bound member function to form a
pointer to member function. Say
'&foo::hello'



cannot convert 'void (foo::)()' to 'void ()()' in assignment




So i tried it like this:



class bar
{
public:
void (*foo::funcP)();
};


But now the compilator adds one more:




'foo' has not been declared




Is there a way make it work?



Thanks in advance for suggestions



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails