Reputation: 23
I have a class that has to store the weight of the animal and it's type. Depending on what the user wants, there can be as many instances of that class created at runtime. My problem is with not being able to properly declare a dynamic array that can resize itself once the entire array has been filled with objects.
class FarmAnimal
{
private:
short int type;
int weight;
double WaterConsumed;
public:
static int NumberOfSheep;
static int NumberOfHorse;
static int NumberOfCow ;
static double TotalWaterUsed;
FarmAnimal(int type, int weight)
{
this->type = type;
this->weight = weight;
}
int CalculateWaterConsumption(void);
void ReturnFarmInfo(int& NumberOfSheep, int& NumberOfHorse, int& NumberOfCow, int& TotalWaterUsed)
};
int main()
{
...
short int k;
...
do
{
...
FarmAnimal animal[k](TypeOfAnimal, weight);
k++;
cout << "Would you like to add another animal to your farm?\n Press\"0\" to exit and anything else to continue" << endl;
cin >> ExitButton;
} while (ExitButton != 0)
and the end of the program
animal[0].ReturnFarmInfo(NumberOfSheep, NumberOfHorse, NumberOfCow, TotalWaterUsed)
cout << " Your farm is made up of :" << NumberOfSheep << " sheeps " << NumberOfHorse" horses " << NumberOfCow << " cows " << endl;
cout << "The total water consumption on your farm per day is: " << TotalWaterUsed << endl;
}
Upvotes: 2
Views: 447
Reputation: 330
Array cannot change size in C++. You need to use a dynamic container such as std::vector
. A documentation of the vector class can be found here.
std::vector<FarmAnimal> animals;
bool done = false;
while (!done)
{
animals.push_back(FarmAnimal(TypeOfAnimal, weight));
cout << "Would you like to add another animal to your farm?\n Press\"0\" to exit and anything else to continue" << endl;
cin >> ExitButton;
done = (ExitButton != 0);
}
Upvotes: 3
Reputation: 177
Use the std::vector
from the standard library and the method push_back()
to add new elements
http://www.cplusplus.com/reference/vector/vector/
Upvotes: 3
Reputation: 11
As mentioned in the comments by Some programmer dude and Ron, variable-length arrays are not supported in C++ by default. The std::vector class is a useful tool should you require them.
Some basic info about vectors: http://www.cplusplus.com/reference/vector/vector/
Upvotes: 0