SetCommand
takes a reference to an ICommand
object. (You can think of references as if they were pointers with different synax for using them, for now). Assuming ICommand
is a parent class of MoveCommand
, you can pass a reference of MoveCommand
(e.g. cmdRight
) to GameEngine::SetCommand()
. In SetCommand()
you will have to convert the type of the passed reference to MoveCommand
in order to be able to assign the value to command
-- otherwise the actual object might have a type that is another child of ICommand
.
Try this:
void GameEngine::SetCommand(ICommand& cmd) {
try {
MoveCommand& mcmd = dynamic_cast<MoveCommand&>(cmd);
command = mcmd;
} catch (const std::bad_cast& e) {
std::cout << "Wrong command passed: move command expected" <<
" (" << e.what() << ")" << std::endl;
}
}
Note: if you do not specifically need a MoveCommand
in GameEngine
, you could declare command
of type ICommand*
and use the passed-in values via the ICommand interface. You will have to dynamically allocate and de-allocate the object, though, so if you are not familiar with that topic, try the above code.