0

I have a class "Horse" with a speed member (1-100). I want the default constructor to generate a random number for the speed, but when I dynamically allocate memory for an array of type Horse, each horse has the same speed.

Here is how I allocated the memory within main:

horsePtr = new Horse[numHorses];

Here is the constructor

Horse::Horse() {
     srand(time(0));
     maxDistancePerSecond = (rand() % 100) + 1;
     distanceTraveled = 0;
     racesWon = 0; }

I know it's a mistake to include srand within the constructor, but the class file won't let me put it anywhere else. How can I get around this?

p.s. I have to use arrays and the srand function (no vectors) :)

Cœur
  • 37,241
  • 25
  • 195
  • 267
wolfeweeks
  • 355
  • 4
  • 12
  • *but the class file won't let me put it anywhere else.* -- Place the call in `main()`. – PaulMcKenzie Apr 02 '20 at 01:51
  • `srand` and `rand` are from the C standard library, and not recommended for use in modern C++. – paddy Apr 02 '20 at 01:54
  • I am a grade A idiot. For some reason, I thought it wouldn't "cross over" to the other file that way. Thanks for sparing my headache @PaulMcKenzie – wolfeweeks Apr 02 '20 at 01:57

0 Answers0