jeudi 1 octobre 2015

Cast Object at Runtime Depending on Instance Variable (C++)

I'm trying to represent a 2 dimensional map of objects. So I have a two-dimensional array of "MapItems":

MapItem world_map[10][10];

In my specific situation, these MapItems are going to be used to represent Drones, Static Objects (like trees or any obstruction that doesn't move), or empty positions (these objects will be subclasses of MapItem):

class Drone : public MapItem {
  int droneId;
  ...
}

class StaticObject : public MapItem {
  ...
}

class EmptyPosition : public MapItem {
  int amount_of_time_unoccupied;
  ...
}

Is it a good idea to have an instance variable on the MapItem class that tells what specific type of item it is, and then cast it the proper type based on that? For example:

enum ItemType = {DRONE, STATIC_OBSTRUCTION, EMPTY};
class MapItem {
  ItemType type;
  ...
}

And then when I want to know what is at a position in the map, I do:

MapItem item = world_map[3][3];
if (item.type == DRONE) {
  Drone *drone = dynamic_cast<Drone*>(&item);
  // Now do drone specific things with drone
  ...
} else if (item.type == STATIC_OBSTRUCTION) {
  StaticObject *object = dynamic_case<StaticObject*>(&item);
  // Static object specific stuff
  ...
} else {
  ...
}

I have not actually tried this, but I assume it's possible. What I'm really asking is this a good design pattern? Or is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire