Why do I can’t make l->set(new StateB); in StateA? (this line is commented below)
It says:
main.cpp: In member function ‘virtual void StateA::writeName(Lap*, char*)’:
main.cpp:19:4: error: invalid use of incomplete type ‘struct Lap’
main.cpp:3:7: error: forward declaration of ‘struct Lap’
but I cant solve that 🙁
#include <stdio.h>
class Lap;
class State;
class StateB;
class StateA;
class State { public:
virtual void writeName(Lap *l, char *str) = 0;
};
class StateB : public State { public:
void writeName(Lap *l, char *str) {
printf("%s B\n", str);
}
};
class StateA : public State { public:
void writeName(Lap *l, char *str) {
printf("%s A\n", str);
//l->set(new StateB);
}
};
class Lap { public:
State *ss;
Lap(){
printf("[Lap]\n");
set(new StateA);
}
void set(State *s){
ss = s;
}
void writeName(char *str){
ss->writeName(this, str);
}
};
int main()
{
printf("\n\n");
Lap lap;
lap.writeName((char*)"Fulano");
lap.writeName((char*)"Fulano");
printf("\n\n");
return 0;
}
The problem is that the forward declaration
only tells the compiler that such a class exists and lets you declare pointers to
Lap, but it does not give the compiler enough information to handle anyLapmethod calls.So you need to have
Lapfully declared before the attempt to use its method.With your code as given this can’t be done in a single file because
Lapdoesnew StateAwhileStateAcalls a method onLap— a circular dependency.You’ll need to move the declarations of at least one (and better yet, all) out to header files and include the headers where needed. Then the compiler will know the full interface details of the classes before either class’s definitions try to use methods in the other class.