Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 982
Mahesh Avatar asked Feb 24 '10 05:02

Mahesh


People also ask

Can we initialize static data member 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.

Why static variables Cannot be initialized 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.

How do you initialize a static data member?

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.

How will you initialize data member using constructor?

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.


2 Answers

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.

like image 83
Naveen Avatar answered Sep 27 '22 23:09

Naveen


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.

like image 42
jamesdlin Avatar answered Sep 27 '22 21:09

jamesdlin