1

I have a Engine class and i want to set a command. This is the header:

class GameEngine
{
public:
GameEngine();
~GameEngine();
MoveCommand command;
void SetCommand(ICommand &);
void Start();
};

The problem is the ICommand. In the main I set the command with

engine.SetCommand(cmdRight);

where cmdRight is a MoveCommand. I don't understand what is passed in the setCommand function.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
marktielbeek
  • 37
  • 2
  • 9

2 Answers2

1

ICommand could be the base class and MoveCommand is a derived class from ICommand so it makes it a valid parameter. It is fairly common to do this when you want to have a generic function but do not know which of the derived classes you will be using. This SO answer explains about inheritance.

Community
  • 1
  • 1
1

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.

Attila
  • 28,265
  • 3
  • 46
  • 55