Your intention is to have a constant
variable inside the class.
Now this class is used to create many objects. Practically the class should allow each object to have different const
value for the const
data member , thus you can't initialize const
members inside class.
const
inside class members means the value is constant throughout the life time of the object.
That is why there exist a special initialization point called constructor initialization list
rather than allowing the initialization in the constructor.
Now, if you're allowed to initialize the const
member inside the constructor then you could re-assign it multiple times within the constructor itself which voilates the meaning of const
(which means, assigned once and remains same throughout).
Hence the initialization of the const
members should happen before the constructor, which is done in the initialization list. This gives you const
members with different values for different objects if you want.
Also, note that the form of initialization in the constructor i(ii)
is used to initialize the data members before entering the constructor
class A
{
const int i;
public:
A(int ii): i(ii)
{
// i = 5; Can't do this since i is `const`
}
};
Having said that, if you want all the object to share the same const
value then you can use static const
qualifier as pointed in others answers.
Also as Mike Seymour pointed out, for allocation of arrays or initializing const
variables you need to have comiple-time constants, but consts
inside class doesn't give you compile time constants, hence you will have to use the static const
qualifier which makes it a compile time constant.