Okay, I'm making a game, and I need to use random inside a class, however I can't figure out how to seed the randomness into the class, so atm I'm getting the same random each time. I've tried stuff like srand(time) in main, however, that doesn't apply to the class, so how am I going to seed it in the class, call srand inside the constructor?

>I've tried stuff like srand(time) in main, however, that doesn't apply to the class
And if you do it in, say, the constructor, what do you expect will happen when you create two objects of that class? The seed is global. Anytime you call srand, the seed will change for every call to rand, regardless of what it applies to in your program's logic.

Depending on your needs, you might want to do one seed at the beginning of main, or you might want to reseed every time an object is created, or you might want to give users of the class the option to reseed at will. But saying that srand should apply to the class is likely to surprise you down the road when it doesn't really apply just to your class.

Edited 6 Years Ago by Narue: n/a

It works if you do it right :

#include<iostream>
#include<ctime>

using namespace std;

class Random{
private: const unsigned int MAX;
public:
	Random(const unsigned int maxLimit) : MAX(maxLimit) {}
	int getRandom(){
		return rand() % MAX;
	}
};

int main(){
	srand(time(0));
	Random myRand(100);

	for(int i = 0; i < 25; i++){
		if(i && i % 5 == 0 ) cout << endl;
		cout.width(3);
		cout << myRand.getRandom() << " ";
	}
	cout<<endl;
	return 0;
}

>I've tried stuff like srand(time) in main, however, that doesn't apply to the class
And if you do it in, say, the constructor, what do you expect will happen when you create two objects of that class? The seed is global. Anytime you call srand, the seed will change for every call to rand, regardless of what it applies to in your program's logic.

Depending on your needs, you might want to do one seed at the beginning of main, or you might want to reseed every time an object is created, or you might want to give users of the class the option to reseed at will. But saying that srand should apply to the class is likely to surprise you down the road when it doesn't really apply just to your class.

Uhm.. Thanks for making me realize that srand is global, somehow it just seems like the pattern were about the same. The output is graphical with OpenGL, so must have like, misschecked it. Thanks. Will mark thread as solved.

This question has already been answered. Start a new discussion instead.