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?

Dani AI

Generated

Short summary: was seeing identical output because the global RNG state was being handled in an unexpected place. correctly pointed out that the seed is global, and showed a working srand-based example. Modern C++ gives safer, clearer patterns to avoid the common pitfalls that cause repeated sequences (especially when you reseed often or seed many objects with the same timestamp).

Prefer one well-seeded engine and reuse it, or explicitly inject an engine into objects that need randomness. This avoids reseeding collisions, avoids the low-quality and modulus bias of rand(), and makes behavior reproducible when you want it. Example — pass a shared RNG into the class (dependency injection):

#include <random>

class RNGUser {
public:
  RNGUser(std::mt19937 &rng, int max)
    : rng_(rng), dist_(0, max - 1) {}
  int next() { return dist_(rng_); }
private:
  std::mt19937 &rng_;
  std::uniform_int_distribution<int> dist_;
};

If you want a self-contained class, create a single static (or thread_local) engine that is seeded once and reused by all instances:

#include <random>

class LocalRNG {
public:
  LocalRNG(int max) : dist_(0, max - 1) {}
  int next() { return dist_(getEngine()); }
private:
  static std::mt19937 &getEngine() {
    static std::mt19937 e{std::random_device{}()};
    return e;
  }
  std::uniform_int_distribution<int> dist_;
};

Troubleshooting tips: do not reseed with low-resolution clocks inside constructors (many objects created in the same second will get the same seed); avoid rand() % n for non-uniformity; use std::random_device to seed mt19937 when you need non-deterministic starts; use a fixed seed when you want reproducible debugging. For OpenGL render loops, create and seed the RNG once (outside the per-frame code) so each frame draws from a continuous sequence.

Recommended Answers

All 3 Replies

>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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.