How do I create an array of classes that all inherit from the same base class

Viewed 136

I'm moving an embedded program from C# to C++ and have been struggling to figure out how to create an array of classes. The program uses a pretty standard "Gang of Four" state pattern. Each of the states is a class that inherits from the base class StateBase. All the state classes reside in an array that I can index as needed. I don't get any errors in the VisualGDB error list but when I compile the program I get this

undefined reference to 'StateBase::StateBase()'

I'm not very experienced in C++ so there's a good chance I'm doing something fundamentally dumb and will appreciate any help.

Here's the base class StateBase:

class StateBase
{
public:
    StateBase();
    virtual void doStateEntryActions();
    virtual void doStateActions();
    virtual StateNames checkEvents();
    virtual void doStateExit(bool timeout);
};

Here's an example of one of the state classes that inherits from StateBase

class Recovery : public StateBase
{
public: 
    Recovery()
    {
        cout << "Recovery constructor" << endl;
    };
    
private:
    void doStateEntryActions()
    {
        cout << "Recovery: doing state entry actions" << endl;
    }
    void doStateActions()
    {
        cout << "Recovery: doing state actions" << endl;
    }
    StateNames checkEvents()
    {
        cout << "Recovery: checking events" << endl;
        return (recovery);
    }
    void doStateExit(bool timeout)
    {
        if (timeout)
            cout << "Recovery: doing state exit with timeout" << endl;
        else
            cout << "Recovery: doing state exit no timeout" << endl;
    }
};

Here's how I define the array

StateBase *stateArray[numStates];
stateArray[recovery] = new Recovery();
stateArray[findNeutral] = new FindNeutral();
stateArray[descend] = new Descend();

And here's how the state machine works:

while (runMission)
{
    if (doStateEntry)
    {
        stateArray[currentState]->doStateEntryActions();
        doStateEntry = false;
    }
    
    stateArray[currentState]->doStateActions();
    nextState = stateArray[currentState]->checkEvents();
    if (nextState != currentState)
    {
        stateArray[currentState]->doStateExit(false);
        currentState = nextState;
    }
}

Thanks is advance for any help.

0 Answers
Related