0

I am actually not really aware if you can declare a class and then use a static instance it among several objects of the same class. More specifically:

class State {
    public:
        State();
        static CustomNumberDist normal_dist;
    private:
        int id;   
};

So every instance of State should contain the same instance of CustomNumberDist. I compiles but I am wondering if it is valid or I may run into problems later on.

Potney Switters
  • 2,902
  • 4
  • 33
  • 51

2 Answers2

6

The declaration (header file i.e. .h) that you have given is perfectly valid.

However in the definition (.cpp file) you need

State::CustomNumberDist normal_dist;

As memory will be required for the static object when you get to the linking stage.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

it is not valid. It should be like :

class X
{
public:
      int normalValue = 5; //NSDMI
      static int i;
};

int X::i = 0;

i needs a place in the memory. In the memory which is not involved with a concrete object .

More information can be find here:

Static Data Member Initialization

Community
  • 1
  • 1
CyberGuy
  • 2,783
  • 1
  • 21
  • 31
  • @delnan In the OP's code, `normal_dist` is not initialized. It is just declared. Its constructor needs to be called and that code will **not** call it. – Mihai Todor Sep 21 '12 at 17:15
  • What does "NSDMI" mean? Also, you should probably mention that in-class initialisation of non-static members (as you do with `normalValue`) is only valid since 2011; or just remove `normalValue` since it has nothing to do with the question. – Mike Seymour Sep 21 '12 at 17:18
  • @MikeSeymour I guess he's referring to "non-static data member initializers", but I'm not a fan of this tendency to abbreviate everything. – Mihai Todor Sep 21 '12 at 17:26