I'm trying to create a state machine; I have a base class State, and another class T that inherits publicly from State. State includes a function pointer. within class T, I want the function pointer to point to a member function of T.
In other words, i Have these headers:
1 2 3 4 5 6 7 8 9 10 11 12
class State {
State (*stateMethod)();
};
class T : public State {
public:
T() { }
T(char*);
~T() { }
private:
State display();
};
in T.cpp I have:
1 2 3
T::T(char* file) {
stateMethod = &T::display;
};
I get the error: "cannot convert `State (T::*)()' to `State (*)()' in assignment "
is there a simple way around this? am I missing something obvious?
It seems you cant just point a State (*fucPtr)() too TitleScreen::display. You would need a State (TitleScreen::*fucPtr)(). So unfortunately, I don't see a workaround.
but every one would have a 'stateMethod' function, right? Couldn't you just put that in every derived class and have it call whatever it needs to from there (in the above example, T::stateMethod could call T::display, but other child classes would do something else with stateMethod).
Well, stateMethod is a pointer to a function, not an actual function, and I wanted this thing to be as flexible as possible, but at this point, I'll probably end up doing that and deal with the issue of changing the target function when and if it ever comes up.
I'm just wondering from a practical standpoint if what you need really is a function pointer. If every child class is going to have a function like this, then that's pretty much exactly what pure virtual functions are for.
edit:
it's also worth noting that virtual functions basically compile to function pointers... so it might actually be what you want, just with simpler syntax than the alternatives.
Right, see this program was originally much simpler, and written in Python, so I was trying to stay true to the function pointer approach, because that's how it was originally written, and it was working; A bit of a redesign seems prudent though.