25

I read the answer in parashift but I need bit details as to why compiler won't allow to define static member variable in constructor.

5 Answers 5

39

static member variables are not associated with each object of the class. It is shared by all objects. If you initialize in ctor then it means that you are trying to associate with a particular instance of class. Since this is not possible, it is not allowed.

0
5

I presume you're referring to using it in an initialization list to a constructor. A static data member is shared among all instances of the class. It can be initialized once (by definition of initialization), so it wouldn't make sense to initialize it for each instance.

You could, however, assign it a value (or mutate the existing value) in the constructor body. Or if the data member is a constant, you can initialize it statically outside of the constructor.

0
0

static variable can't be defined inside any method (even if the method is static) you can however define the static variable outside the constructor and assign a value inside the constructor. But by doing so the variable will then be accessible to the whole class.

0

1) Static variables are property of the class and not the object. 2) Any static variable is initialized before any objects is created.

  • That's why compiler don't allow to define static variable inside constructor as constructor will be called when a object is created.
0
0

A member initialization list denotes initialization. A static member is already initialized at the beginning of your program (before main). If you could do what you are suggesting, you would be "re-initializing" the static member with every object that you create, but objects are only initialized once.

Instead, if you want to change the value of an object after it has been initialized, you have to assign to it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.