2

I have a simple class which will be useful for me with generating random numbers using default_random_engine.

Random.h:

#include <random>

using namespace std;

class Random
{
    public:
        Random();
        ~Random() {}
    private:
        static default_random_engine _engine;
};

Random.cpp:

#include "Random.h"

Random::Random()
{
    _engine = default_random_engine{}; //Will this be initialized every time I create an object of type Random?
}

Will _engine be initialized every time I create an object of type Random? I just want it to stay like it is after the first initialization because I was told I can use the same engine multiple times.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Eyal
  • 1,649
  • 3
  • 25
  • 49
  • @NathanOliver Thanks, you helped me understand. – Eyal May 05 '16 at 15:02
  • 2
    If that `using namespace std;` is there for reasons other than making the code in this very question shorter: Please don't. Putting it in a `.cpp` is already bad enough, but in headers, it's rather unacceptable. – Baum mit Augen May 05 '16 at 15:04
  • 1
    @BaummitAugen Thanks for letting me know! – Eyal May 05 '16 at 15:08

2 Answers2

3

Will _engine be initialized every time I create an object of type Random?

Yes.

I just want it to stay like it is after the first initialization

In which case, you should define it like so:

#include "Random.h"

std::default_random_engine Random::_engine;

Without this, even your original version won't compile (as you've not defined the static member).

OMGtechy
  • 7,935
  • 8
  • 48
  • 83
0

The link @NathanOliver provided in my question helped me understand, which is to make a global variable of that type in the source file:

#include "random.h"

default_random_engine Question::_engine = default_random_engine{};

Random::Random() {  }
Eyal
  • 1,649
  • 3
  • 25
  • 49