Why can const members be modified in a constructor?

前端 未结 3 558
眼角桃花
眼角桃花 2020-12-15 15:22

I\'m curious why const members can be modified in the constructor.

Is there any standard rule in initialization that overrides the \"const-ness\" of a member?

<
3条回答
  •  抹茶落季
    2020-12-15 15:48

    When you do:

    struct Bar {
        const int b = 5; // default member initialization
        ...
    };
    

    You are telling the compiler to do this with the default constructor:

    ...
    Bar() : b(5) 
    {}
    ...
    

    Irrespective of if you've provided the default constructor or not. When you do provide default-constructor and the initial assignment, you override compiler's default assignment code (i.e. b(5)). Default initialization/assignment at the declaration is useful when you have multiple constructors, and you may or may not assign the const members in all constructors:

    ...
    Bar() = default; // b=5
    Bar(int x) : b(x) // b=x
    Bar(double y) : /*other init, but not b*/  // b=5
    ...
    

提交回复
热议问题