I created a class called bunny. The bunny object contains info such as name, sex,color,age. Each piece of info is randomly created when the bunny is initialized from the bunny class. Now I'm trying to create multiple new bunny objects that would not be the same as the first one that was created also while placing them into a vector.
It's best to use vectors when you can but for reference (and because I have too much time) if you plan on using the bunny class again you could make another class to create and hold an array of bunny objects like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//example class header file "BunnyArray.h"
constint ARRAY_SIZE = 10;
class BunnyArray
{
class tooManyBunnies{}; //exception class arrays have no bounds checking
Bunny(); //basic constructor
~Bunny(); //basic destructor
Bunny getBunny(int index); //get a particular bunny
private:
Bunny *arrayOfBunny[ARRAY_SIZE]; //your bunny array
};
//bunny.cpp
// this code makes ten bunny objects
Bunny::Bunny()
{
for (int i = 0; i < arraySize; i++)
bunny[i] = new Bunny();
}
Bunny::~Bunny()
{
for (int i = 0; i < ; i++)
delete arrayOfBunny[i];
}
Bunny Bunny::getBunny(int index)
{
Bunny *tmpBunny = new Bunny();
if (index > ARRAY_SIZE || index < 0)
throw TooManyBunnys();
*tmpBunny = arrayOfBunny[index];
return *tmpBunny;
}
Then in Main all you would have to do to create a bunny array is this
main()
{
BunnyArray *bunnies = new BunnyArray;
Bunny *bunny = new Bunny;
//now you have an array of non initialized bunnys you would need a
//set bunny method as well to have an array of mixed bunnies
//now to get a bunny out of your array
try
{
bunny = bunnies->getBunny(4);
}
catch(tooManyBunnies::tooManyBunnies)
{
cout << "array index past array size too many bunnies!"
}
return 0;
}
I tried what @moschops suggested already and it just gives me a bunch of the same bunny. I want to use the same class again so that it will create another bunny without me creating another variable for it. I am using a vector already but I still get a bunch of the same bunnies
How are you making each bunny object different? These all come out with different, randomly generated age values. How do you know each created bunny object you make has different values?
With the help of the above comment I figured out that srand was in the wrong location. Also the bunnies weren't different, that was the problem. Thanks for everyone's help