0

I have a class that represents a checking account, and in the checking account there is a class member that represents an account number. This account number is initialized in the constructor (random numbers obviously) for several different objects. I am having difficulties getting different numbers for each object. Mainly because I am just starting out in C++ and I implemented this RNG idea via several posts I have viewed here on SO.

Here is my constructor:

CheckingAccount::CheckingAccount(const Customer& owner): Account(owner){
    srand ( time(NULL) );
    int acctStartNum = 9;
    int firstDigit = rand() % 10;
    int secondDigit = rand() % 10;
    int thirdDigit = rand() % 10;
    int fourthDigit = rand() % 10;

     ostringstream oss;
     oss << acctStartNum << firstDigit << secondDigit << thirdDigit << fourthDigit;
    accountNumber = stoi(oss.str());

}

I understand srand() seeds the random numbers to provide a nice spread of values each time. But when I had excluded it from my code, each object had a different accountNumber. The catch though was, that each time I ran my program the values never changed (i.e. it generated random values for each object only once and then kept those values), which is why I implemented srand(), but now all objects have the exact same accountNumber, granted they change each time I run the program. What is the deal here? Why were they all different before I implemented srand() and never change, but now they change but apply to all objects? Also just as a side note, I know this may look quite sloppy, but this is for an assignment that instructs me to do this IN the constructor, otherwise I'd make a function.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
LumberSzquatch
  • 1,054
  • 3
  • 23
  • 46
  • 1
    [Don't call `srand()` more than once!](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/) – Jonathan Leffler Feb 18 '15 at 23:23
  • 2
    You should probably call `srand ( time(NULL) );` outside of your class (e.g. in `main()`), unless you're sure you construct only a single object of it. – πάντα ῥεῖ Feb 18 '15 at 23:24
  • @πάνταῥεῖ, This did it. It's always something simple that does the trick. Thank you, I figured the problem lied in my lack of understanding. – LumberSzquatch Feb 18 '15 at 23:30

1 Answers1

0

srand should be called only once before any random number is generated. It should not be called again. Otherwise, your numbers won't be as random as you want them to be.

Mido
  • 665
  • 10
  • 20