Reputation: 1302
I'm having trouble getting the std list class to call the proper function on a class. It keeps calling the base class' function only. Here's what's happening:
I have a state class with the following update function which is declared virtual in the header:
State.h update function:
virtual void update(float elapsed);
State.cpp update function:
void State::update(float elapsed){
};
and a class that inherits from it called TestState:
class TestState::public State{
virtual void update(float elapsed){
if (GLOBALENGINE->getInput() -> getKeyPress(DIK_Q)
PostQuitMessage(0);
};
};
I call the addState function to add a new state to the linked list and make it the current state as follows:
GLOBALENGINE->addState(new TestState,true);
The addState function looks like this:
void GameEngine::addState(State *state, bool change){
states->push_back(*state); //add the test state into the states list
// some irrelevant code
currentState = &(states->back());//currentState is a pointer to a State
// So we make it point to the newly added state.
}
Then the run() function is called every frame and inside of it is the following code:
currentState->update(elapsed)// This should call the update function in TestState!
I thought that this line should call the update function in TestState but instead it calls only the function in the State class (ie: it does nothing).
Can someone explain how I can get the functionality I'm looking for?
Thanks
Upvotes: 0
Views: 83
Reputation: 3902
You should store in the list a pointer (or a smart pointer) to your object, not an object directly, or you lose polymorphism. In
states->push_back(*state);
you are instructing push_back
to construct a copy of state
and add the copy in states
. The copy is of type State
, not TestState
, and thus does not behave the same way.
This behaviour is called object slicing; see for example this SO question.
Upvotes: 5