Ell
Ell

Reputation: 4376

C++ Vector Of Base Class Containing Derived Types

I have a several classes DemandBuilding, Factory, Farm and some others. I want to store instances of these in a single 2d array, I did this by making a base class, Building, which does nothing but allows me to do this: (Note that the second vector is because it is a 2d vector for storing these buildings on a map)

vector<vector<Building*> > map;

Instead of this:

vector<vector<DemandBuilding*> > demand_buildings;
vector<vector<Factory*> > factories;
vector<vector<Farm*> > farms;
//etc...

(I'm away from my computer so I'm not sure that this is legal C++, although I think it is) To me this looks like an incorrect use of inheritance, is it?

EDIT: Thanks for helping that there is nothing conceptually wrong with this but I have since realized that doing this wont help my situation, thanks anyway.

Upvotes: 1

Views: 980

Answers (2)

Hovhannes Grigoryan
Hovhannes Grigoryan

Reputation: 1151

The second vector is not needed, just use:

vector<Building*> buildings;

And for 2d array you can have:

vector< vector<Building*> > buildingMatrix;

or if you know the size of the 2d array at compile time:

Building* buildingMatrix[SOME_CONST_SIZE_1][SOME_CONST_SIZE_2];

So you can have here pointers of all your buildings.

Also you may consider putting all the common methods of your diffident buildings into base class Building. Make them virtual as appropriate, use virtual destructor in case you will need to delete particular building correctly with Building pointer.

Upvotes: 0

Erik
Erik

Reputation: 91320

Conceptually there's nothing wrong with this - it all depends on how you use it. If you find yourself having to cast a lot, you may need to rethink the design.

Also, you very likely should have a virtual destructor, if you delete a Building * and the destructor isn't virtual, the subclass destructor is not executed.

Upvotes: 1

Related Questions