I am working on a C++ class that uses a rand()
in the constructor. I would really like for this class to take care of itself in pretty much every way, but I'm not sure where to seed rand()
.
If I seed rand()
in the constructor, it will be seeded every time a new instance of my object type is constructed. So if I were to create 3 objects in sequence, they would all be created in the same second and therefore have the same seed for rand()
, producing the exact same data for each of the 3 instances of the object.
I would like to seed rand()
within the class code, rather than having to do it in the main function of my program before I create the object. I thought of doing a static bool seeded;
variable that signifies whether or not rand()
has been seeded yet, but I'm not really sure how to initialize it to false at the creation of the class.
My idea goes something like
myConstructor(){
if(!seeded){
srand(time(NULL));
seeded = true;
}
myVariable = rand()%maxVal;
}
I think this would work if I could just figure out how to initialize the static value to false a single time at the start of the program. It is my understanding that changing this static value to true would carry across all instances of the object if it were static, and would therefore only execute the seed function the very first time that object type is created.