Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is initialization of integer member variable (which is not const static) not allowed in C++?

My C++ compiler complains when i try to initialize a int member variable in class definition. It tells "only static const integral data members can be initialized within a class". Can you please explain the rationale behind this restriction (if possible with example).

like image 624
Sulla Avatar asked Dec 01 '10 09:12

Sulla


People also ask

Why is initializing a class member variable during declaration not permitted?

The main reason is that initialization applies to an object, or an instance, and in the declaration in the class there is no object or instance; you don't have that until you start constructing.

Where do you initialize a non static class member that is a reference?

Member initialization Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.

Is it necessary to initialize const variables?

A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration.

Why we Cannot initialize data members within the class?

Answer: When we declare/write a class, there is no memory allocation happens for data members of a class, so, we cannot store data into data members. The memory gets allocated for data members only when we create objects of a class.


3 Answers

Because it's not allowed in the current standard. According to Bjarne, you will be able to do this in C++0x. If you really need it, try setting the compiler to C++0x (-std=c++0x in GCC) and see if your compiler supports it.

like image 172
beldaz Avatar answered Oct 15 '22 13:10

beldaz


The rationale is the "low-level" nature of C++. If it would allow this, the compiler would need to generate initialization code for all constructors which is not entirely clear to the developer.

After all it might be necessary to initialize members of base classes on the construction of a derived class even when the base class constructors are not explicitly invoked.

Static const integral variables do not need intitalization upon object creation.

like image 8
Tomas Avatar answered Oct 15 '22 11:10

Tomas


The static restriction exists because C++ uses constructor initializers to initialize non-static data members:

struct Example {
  int n;
  Example() : n(42) {}
};

The const restriction exists because the const case is treated specially (rather than the other way around) so that static const integral members can usually be treated as if they had internal linkage, similar to const variables at namespace scope (C++03 §7.1.5.1p2, if you're interested). This is primarily beneficial to use the members in integral constant expressions, such as array sizes.

like image 4
Fred Nurk Avatar answered Oct 15 '22 13:10

Fred Nurk