-1

I have read that constructors can inizialize only non static attribute. I have written a small code to check that and Im wondering now because the compiler dosnt show any error??? So Can I initialize static attribute and non static attribute in the constructor or not? this is my code! Thank you very much!

class NixIs {
    int var;
    static int global;
public:
    NixIs(int val = 0) 
    {
        global = val;
    }

2 Answers2

3

I think you mean "field" instead of "attribute"

Your code is valid C++ but it does not initialize the static field global, as it's an instance constructor.

If you want to initialize NixIs::global with a trivial constant value (known at compile-time) you can specify it inline in the header:

NixIs.h:

class NixIs {
    static int global = 0;
}

If you have a non-constant initial value (such as a parameterless free-function result) then the static field initializer needs to be in a code-file (instead of a header). You need to specify the static field in addition to its type and the initial value of the static field:

NixIs.h:

class NixIs {
    static int global;
}

NixIs.cpp:

int NixIs::global = nonTrivialValue;

If you want to initialize multiple static fields in a particular order or with function-result values you'll need to use a hack because C++ does not have static constructors. See here: Static constructor in c++

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 4
    You can use `static int global = 0;` only for `const` members, i.e. `static int const global = 0;`. – R Sahu Jan 12 '16 at 23:55
  • 1
    Defining in headers, you can get a number of copies of the value in binaries, which may or may not be what you want. – Jason Jan 12 '16 at 23:58
  • If you want to initialize multiple static fields in a particular order, simply place the definitions in a single cpp file in that order*. *Technically there's several passes at initialization, but effectively, just this. – Mooing Duck Jan 13 '16 at 00:05
0

Initializing an attribute in a constructor is usually done using the initializer list. For instance, you could initialize the non-static attribute in your class like this:

NixIs( int init_val) : val(init_val) {
  // do stuff
}

I think that is what you meant. Trying to initialize a static class member like this would be an error. However, all class methods including constructors and destructors can access static members. In your example, 'global' would simply be overwritten with each new instance that is created.

NixIs first(1); // first.global is now 1
NixIs second(2); // first.global is now also 2 (same as second.global)
Jochen Müller
  • 309
  • 1
  • 6