Consider the code snippet
class Test{
const int i;
public:
// Test(int x):i(x){} This works
Test(int x){
i=x;
} //this doesn't work
Why does the inline member initialization list work while the normal initialization doesn't work?
Consider the code snippet
class Test{
const int i;
public:
// Test(int x):i(x){} This works
Test(int x){
i=x;
} //this doesn't work
Why does the inline member initialization list work while the normal initialization doesn't work?
Note that i=x;
is an assignment. If you doesn't initialize it via member intializer list, i
will be tried to be default-initialized, then assigned in the constructor's body.
But as a const variable, i
can't be default-initialized (or assigned). So it has to be specified in the member intializer list for initialization.
Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.