I’m having a hard time getting this working in C++, I’ve managed it in C# but I’ve not used C++ much so I’m not sure on the syntax.
The purpose of this is for a simple state manager, each state inherits from a base class called “state”.
I’ve gotten overriding to work but I can’t seem to manage the polymorphism aspect. That is that I cannot have an object “State currentState” and set that object to equal “menuState” and have it run the desired function, I know this is because it is only finding the signature for the State class but I am unsure how to avoid it. Here’s some simplified code so that someone can help me understand.
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// State.h
class State{
public:
virtual void drawState();
};
// State.cpp
void State::drawState() {
cout << "Base state.\n";
}
// MenuState.h
class MenuState: public State {
public:
virtual void drawState();
};
// MenuState.cpp
void MenuState::drawState() {
cout << "Menu state.\n";
State::drawState();
}
int main ()
{
State currentState;
MenuState menuState;
currentState = menuState;
currentState.drawState();
system("pause");
return 0;
}
If you change “State currentState” to create an object of MenuState the code will work as I require it to, however I need it to be the parent class so that I can set the current state to other states I will create in the future such as GameState.
Thank you.
Polymorphism doesn’t work with plain objects because of slicing. You have to use references or (smart) pointers. In your case, pointers, as references can’t be re-assigned:
In your code:
the assignment slices
menuState– it basically just copies theStatepart of it tocurrentState, losing all other type information.