What is the correct way of doing this? I don't want to change the structure... I just need to know the correct syntax. Been reading online but its just a bit confusing... can you help?
#include <functional> // C++11, your compiler probably supports it. If not, upgrade.
class fruit {
public:
std::function<bool(int)> eat;
};
class worm {
//...
dinner.eat = std::bind( &worm::nibble, std::ref(*this), std::placeholders::_1 );
3) Use "traditional" C++ function pointers (RESTRICTION: only works if 'worm' is the only class that will be eating fruit)
The syntax for this is really funky and hard to remember so I won't post an example unless you're really interested. But given the restriction, I doubt it will be what you need.
options 2 and 3 are still available. I don't know why you "can't"... you have an internet connection, don't you? ;P Or are you forced to work with someone else's toolset (like for a job or something)
Anyway, Option 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class theform;
class engine{
public:
bool (theform::*pf)(int i);
theform* obj;
// called with:
// (obj->*pf)( xx );
};
class theform: public f {
//...
void setFormDefaults() {
e.pf = &theform::h;
e.obj = this;
//...
As you can see, this approach is cumbersome because you have to keep track of that object pointer, and it only works for the 'theform' class. If you have a different function in a different class that you want to point to, this won't work.
};