2

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
user3762146
  • 205
  • 3
  • 13
  • What you call "the normal initialization" isn't an initialization. There are plenty of posts hare about initializing data members. – juanchopanza Mar 13 '17 at 07:16
  • 1
    `i = x;` is not **initialization**. It is **Assignment**. And you can change value of const variables. – JustRufus Mar 13 '17 at 07:18
  • Possible duplicate of [Uninitialized constant members in classes](http://stackoverflow.com/questions/4343934/uninitialized-constant-members-in-classes) – Jonas Mar 13 '17 at 07:18

1 Answers1

2

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405