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.
If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the 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.
The initializer for a static data member is in the scope of the class declaring the member. A static data member can be of any type except for void or void qualified with const or volatile . You cannot declare a static data member as mutable . You can only have one definition of a static member in a program.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With