-4

When attempting to randomly generate a string for a name attribute in a class, the output seems to print the same string for each object.

When I run this in the debugger, a unique name identifier IS generated for each Array object, however, when compiling and running the program, the name attribute is the same for both objects. Any help on why this may be happening would be much appreciated. Thanks!

Main:

int main() {
  Array One(3);
  Array Two(5);
  cout << One.getName() << endl;
  cout << Two.getName() << endl;

  return(0);
}

Header file:

public:
   Array(int arraySize= 10);              // default constructor
   Array(const Array &init);              // copy constructor
   ~Array();                              // destructor

   void setName();                          // set objects w/ unique names
   int getCapacity() const;                 // return capacity
   int getNumElts() const;                  // return numElts
   string getName() const;                  // return name
   void incrementNumElts();                 // increment numElts
   void incrementCapacity();                // increment capacity

private:
   int capacity,        // capacity of the array
       numElts;         // Elements in the array in use
   int *ptr;            // pointer to first element of array
   static int arrayCount;   // # of Arrays instantiated
   string name;
};

Default Constructor in .cpp file:

Array::Array(int arraySize) {
  setCapacity(( arraySize > 0 ? arraySize : 10 ));
  setNumElts();
  setName(); /* Giving each object a unique identifier.
              Note: names will be different from the variable names in the
              code. This will just make the prints a bit more clear about
              which objects are being appended, copied etc.. */
  ptr = new int[getCapacity()]; // create space for array
  assert( ptr != 0 );    // terminate if memory not allocated
  ++arrayCount;          // count one more object
}

The set function:

void Array::setName() {
  srand(time(NULL));
  string Str;

  static const char alphanum[] =
  "0123456789"
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "abcdefghijklmnopqrstuvwxyz";


  for(int i = 0; i < 4; ++i) {
    Str += alphanum[rand() % sizeof(alphanum)-1];
  }
  name = Str;
}

The get function:

// Get unique identifier of array object
string Array::getName() const {
  return name;
}

1 Answers1

3

You call srand(time(NULL)) every time. That seeds the random number generator. If you call it within the same second, it has the same seed, and produces the same results.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131