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).
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.
Member initialization Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.
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.
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.
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.
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.
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.
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