开发者

Why can't I initialize my static data member in my constructor

I read th开发者_如何学运维e answer in parashift but I need bit details as to why compiler won't allow to define static member variable in constructor.


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.


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜