I'm writing a simple class for atoms objects. Here's what I've written so far:
#include <random>
class Atom {
int mSpin;
public:
Atom();
Atom(int);
Atom(const Atom&);
~Atom() {}
Atom& operator= (const Atom &atom);
};
And the .cpp file:
include "Atom.h"
Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}
/* OPERATORS */
Atom& Atom::operator= (const Atom ©) {
mSpin = copy.mSpin;
return *this;
}
I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here. Usually I'd do something like this:
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);
but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?
Hope the question is clear.
You should make the random device and generator static members of the Atom class. This way, like global variables, they are initialized only once for the duration of your program.
class Atom {
// declaration
static std::random_device rd;
static std::mt13397 gen;
...
};
// definition - this must be in Atom.cpp
std::random_device Atom::rd;
std::mt13397 Atom::gen(Atom::rd());