This is a general programming question. I’m learning about C++ and I’ve learned that any const variables, ie: const int i, or int *const ptr, have to be initialized right away.
This is also the underlying reason that references to addresses must be initialized right away, because the addresses are const.
But I can’t find the reason why this must be done / why this rule is imposed.
Can anyone explain this for me please?
Because there is no way you can initialize it, or assigned with a value, later on.
Now if a variable which is neither having any meaningful value, nor are you allowed to make it to have value later on because it is a const variable, then what is the point of such a variable? It is completely useless.
However, this is true for only built-in and POD types:
Actually a NON-POD type cannot remain uninitialized, because the default constructor will be called, and the object would get initialized.
Now consider this struct,
Cis definitely a non-POD type, because it has user-defined constructor. Also note that in the constructor, it doesn’t initializeiwhich isint, declared asconst. Because of this uninitializedconsti, the following would give error:One might think the error is because of
constin the above declaration of variablec. But that is short-sightedness and is not true. Even if you removeconst, it would give error:The error is because of
C::iwhich is declaredconstbut has not been initialized.Demo : http://ideone.com/NJT8L
This analysis also demonstrates that built-in types do not get initialized automatically even if they’re members of non-POD types. This is true of non-POD class types as well.
And the syntax to default initialization for built-in types (and POD types) is this:
Now this is allowed :
Demo : http://ideone.com/84vD9
As for what makes a struct/class POD, see this topic: