Here I have state_machine.h:
#ifndef STATE_MACHINE_H
#define STATE_MACHINE_H
// state machine classes
//#include "state_t.h"
class state_t;
class state_machine
{
public:
state_machine();
void change_state(state_t *newState);
void process_state(int data);
private:
state_t *_state;
};
#endif // STATE_MACHINE_H
And here is state_t.h:
#ifndef STATE_T_H
#define STATE_T_H
#include <QByteArray>
#include <QDebug>
//#include "state_machine.h"
class state_machine;
class state_t
{
public:
state_t(QByteArray stateName);
virtual ~state_t();
virtual void processState(state_machine *sm, int input) = 0;
void defaultUnknownEventHandler(int event);
QByteArray name;
};
#endif // STATE_T_H
Then some state classes, which are all the same more or less, I'll just list one:
teststate1.h:
#ifndef TESTSTATE1_H
#define TESTSTATE1_H
#include "state_t.h"
class testState1 : public state_t
{
public:
testState1();
void processState(state_machine *sm, int event);
};
#endif // TESTSTATE1_H
teststate.cpp:
#include "teststate1.h"
#include "teststate2.h"
testState1::testState1() :
state_t("state1")
{
}
void testState1::processState(state_machine *sm, int event)
{
qDebug() << name << ": event" << event;
switch (event)
{
case 2:
{
// error: invalid use of incomplete type 'class state_machine'
sm->change_state(new testState2());
break;
}
default:
{
defaultUnknownEventHandler(event);
break;
}
}
}
The problem:
I am trying to tidy up my code and use the minimal amount of header inclusion (especially in header files) by using forward declarations. You can see in the state_machine class header I have commented out #include "state_t.h"
and replaced it with a forward declaration class state_t;
. This worked and my code compiled and ran.
Then, in state.h I replaced #include "state_machine.h"
with a forward declaration class state_machine;
(you can see where I commented it out).
But now I get the error error: invalid use of incomplete type 'class state_machine'
which I have commented in testState1.cpp code. But I am not sure why. Why is state_machine an incomplete type?