0

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?

1 Answers1

1

A "switch on type" indicates a design problem much more often than not.

What you usually want to do is define and implement some virtual functions for the behaviors you care about. For example, you might care about flying into one of the spaces. If so, you might have a function to see if it allows entry. That will return true if a drone is trying fly into open air, or false if it's trying to fly into a tree.

As an aside, if you're going to have derived objects, you need to define the array as container pointers, not actual objects of the base class. Otherwise, when you try to put a derived object into the array, it'll get "sliced" to become an object of the base class.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111