The problem is that your push_back()
calls are not pushing the correct values that the various vector
s are expecting.
vector<Food*>
expects you to push_back()
a Food*
but you are trying to push a Resource*
instead.
vector<Water*>
expects you to push_back()
a Water*
but you are trying to push a Resource*
instead.
vector<Mine*>
expects you to push_back()
a Mine*
but you are trying to push a Resource*
instead.
vector<Medical*>
expects you to push_back()
a Mine*
but you are trying to push a Resource*
instead.
Yes, you are creating objects of type Food
, Water
, Mine
and Medical
, respectively. But you are assigning all of them to Resource*
variables, and that is where the error is originating from. None of your vector
s are expecting Resource*
.
Try this instead:
class Grid {
private:
int size;
char** grid;
int noofsupplies; //determined by the grid size.
vector<Food*> food;
vector<Water*> water;
vector<Mine*> mine;
vector<Medical*> medical;
public:
Grid(int sizeofgrid)
: size(0), grid(NULL), noofsupplies(0)
{
size = sizeofgrid;
noofsupplies = 3 * ((sizeofgrid * sizeofgrid) / 25);
grid = new char*[size];
for (int i = 0; i < size;i++)
grid[i] = new char[size];
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j)
grid[i][j] = '-';
}
for (int i = 0; i < noofsupplies; ++i) {
food.push_back(new Food);
water.push_back(new Water);
mine.push_back(new Mine);
medical.push_back(new Medical);
}
deploy_resources(); //place the food inside the map..
}
Grid(const Grid &src)
: size(0), grid(NULL), noofsupplies(0)
{
size = src.size;
noofsupplies = src.noofsupplies;
grid = new char*[size];
for (int i = 0; i < size; ++i)
grid[i] = new char[size];
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j)
grid[i][j] = src.grid[i][j];
}
for (int i = 0; i < noofsupplies; ++i) {
food.push_back(new Food(*(src.food[i])));
water.push_back(new Water(*(src.water[i])));
mine.push_back(new Mine(*(src.mine[i])));
medical.push_back(new Medical(*(src.Medical[i])));
}
deploy_resources(); //place the food inside the map..
}
~Grid() {
for (int i = 0; i < size; ++i)
delete[] grid[i];
delete[] grid;
for (int i = 0; i < noofsupplies; ++i) {
delete food[i];
delete water[i];
delete mine[i];
delete medical[i];
}
}
Grid& operator=(Grid rhs) {
swap(*this, rhs);
return *this;
}
};
Which can be greatly simplified by getting rid of all the new
and delete
calls, let the compiler and STL handle all of the memory allocations and releases for you:
class Grid {
private:
vector<vector<char> > grid;
vector<Food> food;
vector<Water> water;
vector<Mine> mine;
vector<Medical> medical;
public:
Grid(int sizeofgrid) {
grid.resize(sizeofgrid);
for (int i = 0; i < sizeofgrid; ++i)
grid[i].assign(sizeofgrid, '-');
int noofsupplies = 3 * ((sizeofgrid * sizeofgrid) / 25);
food.resize(noofsupplies);
water.resize(noofsupplies);
mine.resize(noofsupplies);
medical.resize(noofsupplies);
deploy_resources(); //place the food inside the map..
}
};