I am working on a C ++ class that uses the rand() constructor in the constructor. I would really like this class to take care of itself in almost every way, but I'm not sure where the rand() seed is.
If I have a rand() seed in a constructor, it will be sown every time a new instance of my object type is created. Therefore, if I were to create 3 objects in a sequence, they would all be created in one second and therefore would have the same seed for rand() , creating accurate data for each of the three instances of the object.
I would like the rand() seed in the class code, instead of doing this in the main function of my program, before I create the object. I was thinking of making a static bool seeded; , which means that rand() has not yet been seeded, but I'm not sure how to initialize it to false when creating the class.
My idea is like
myConstructor(){ if(!seeded){ srand(time(NULL)); seeded = true; } myVariable = rand()%maxVal; }
I think this will work if I just can figure out how to initialize a static value to false at a time at the beginning of the program. I understand that changing this static value to true will go through all instances of the object, if it was static, and therefore will only perform the initial function the first time an object type is created.
source share