Using rand() ina class

Hi!

I was building a simple example of a class that represents a "dice".
At this point i have:
Dice.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdlib>
#ifndef DICE_H
#define DICE_H
class Dice{
public:
	Dice(){
		faceup = ThrowDice();
	}
	int getFace(){
		return faceup;
	}
	int ThrowDice(){
		faceup = rand()%6+1;
		return faceup;
	}
private:
	int faceup;
};
#endif 

And i tested it with ...
game.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <ctime>
#include "Dice.h"
using namespace std;
int main(){
	int i;
	Dice A, B;
	for(i=0; i<10; i++){
		A.ThrowDice();
		cout << A.getFace() << endl;
	}
}


The problem is that i get always the same numbers.
How can i make the number generation more random without complicating too mush (because that is not the main subject here)?

Showl i use srand ant time?!

Thanks
srand( time( 0 ) );

as the first line in main().



I would suggest calling srand(time(0)) in the class constructor
Last edited on
That would reseed the RNG every time a Dice was constructed and would go against the rule of seeding only once.
Not if done in this way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Dice
{
    static bool init;
    public:
        Dice()
        {
            if(!init) 
            {
                init = true;
                srand(time(0));
            }
            // ...
        }
    //...
};
bool Dice::init=false;

So the programmer can use the Dice class without calling srand

(Edit) What's wrong in seeding few times?
Last edited on
It is recommended that the RNG be seeded only once to generate "better" RNGs.

The above works, though I still would advocate moving the srand() to main() because now only Dice can call srand() in the entire application (which might not be a problem for the above application, but then consider a larger application that has a Coin class and a Flip() method -- now does Dice init the RNG, or does Coin, or both, or neither?). I don't think it should be Dice's responsibility to do that. In a truly object oriented, flexible architecture I would allow the user to construct a Dice with a random number generator function (using rand() as the default) along the same lines as the random_shuffle() standard algorithm.
I will use srand() in main, because otherwise i will be running away from my initial idea.

One of this days, with a little more time, i will try adding a "shuffle" method to the class so that who decides to use the class as not to worry about about the way random numbers are generated.

Thanks again
Topic archived. No new replies allowed.