Reputation: 10728
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.
Upvotes: 26
Views: 27063
Reputation: 861
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.
Upvotes: 0
Reputation: 830
1) Static variables are property of the class and not the object. 2) Any static variable is initialized before any objects is created.
Upvotes: 0
Reputation: 8568
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.
Upvotes: 0
Reputation: 89965
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.
Upvotes: 5
Reputation: 73443
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.
Upvotes: 40