#include <iostream>
class Core;
class State;
int main (){
std::cin.get();
return 0;
}
class State{
public:
State(Core* core){
core->setState();
}
};
class Core{
public:
Core(){
State state(this);
}
void setState(){
std::cout << "setting state" << std::endl;
}
};
I keep getting the "use of undefined type" error. I thought that if I forward declare both of the classes, it would fix the problem but I can't figure it out. Is it just silly c++ syntax that I'm missing?
EDIT: Sorry about the gamestate typo, I've changed it to State and it still produces the error.
In State::State
, you are using Core
before it is actually defined. You can fix this easily in your example by moving the constructor implementation out of the class definition:
class State{
public:
State(Core* core);
};
class Core{
// This stays the same...
};
State::State(Core* core)
{
core->setState();
}
It's much more common in practice to have the implementation of these functions in a separate implementation (.cpp
) files, in which case the forward declarations would work as you've expected.
In that case:
// State.h
class Core;
class State{
public:
State(Core* core);
};
And
// Core.h
#include "State.h"
#include <iostream> //This is probably a good reason to further separate
//Core.h into Core.h and Core.cpp
class Core{
public:
Core(){
State state(this);
}
void setState(){
std::cout << "setting state" << std::endl;
}
};
And the implementation file:
// State.cpp
#include "State.h"
#include "Core.h"
State::State(Core* core)
{
core->setState();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With