I'm trying to store the reference of the class "Randomer" initiated in "main" to another class.
What would be best approach, the pointer or reference?
How does the class "Randomer" takes is initial values.
How does this work?
operator()()
size_t operator()() {
return dist_(gen_);
}
Randomer taken from: https://www.mmbyte.com/
class Randomer {
// random seed by default
std::mt19937 gen_;
std::uniform_int_distribution<size_t> dist_;
public:
/* ... some convenient ctors ... */
Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
: gen_{seed}, dist_{min, max} {
}
// if you want predictable numbers
void SetSeed(unsigned int seed) {
gen_.seed(seed);
}
size_t operator()() {
return dist_(gen_);
}
};
someClass{
protected:
Randomer& random;
public:
someClass(){
this->random = ....; // <----------------------
this->random{0, 9}; // this doesn't work.
}
someClass(Randomer& random){
this->random = random; // <----------------------
}
}
int main()
{
Randomer randomer{0, 9}; // how does this work?
someClass* test = new someClass(randomer);
int randomNumber = randomer(); // // how does this work?
std::cout << "randomNumber" << randomNumber << endl;
return 0;
}
Result in error:
error: constructor for 'someClass' must explicitly initialize the member 'random' which does not have a default constructor.
The error applies to default constructor as the overloaded constructor.
Edit: If I try reference:
someClass{
protected:
Randomer& random;
public:
someClass(): : random(new Randomer{0,9}){ // this doesn't work either
}
someClass(): random{0}{ // <------ error 1
}
someClass(): random{0,9}{ // <------ alternative, error 2
}
someClass(Randomer& random): random(random){ // all good
this->random = random;
}
void somefunction(){
int randomNumber = this->random(); // no complaing
}
}
int main()
{
Randomer randomer{0, 9}; // is created here
someClass* some = new someClass;
someClass* some2 = new someClass(randomer);
}
Error:
1: No matching constructor for initialization of 'Randomer &'
2: Non-const lvalue reference to type 'Randomer' cannot bind to an initializer list temporary
The default constructor needs "Randomer"
otherwise error:
Constructor for 'someClass' must explicitly initialize the reference member 'random'.
I would like to have both constructors.
The best bet is to get via reference.