Why can const members be modified in a constructor?

前端 未结 3 567
眼角桃花
眼角桃花 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:55

    This is not modification (or assignment) but initialization. e.g.

    struct Bar {
        const int b = 5; // initialization (via default member initializer)
        Bar(int c)
            :b(c)        // initialization (via member initializer list)
        {
            b = c;       // assignment; which is not allowed
        }
    };
    

    The const data member can't be modified or assigned but it could (and need to) be initialized via member initializer list or default member initializer.

    If both default member initializer and member initializer are provided on the same data member, the default member initializer will be ignored. That's why b->b is initialized with value 2.

    If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

    On the other hand, the default member initializer takes effect only when the data member is not specified in the member initializer list. e.g.

    struct Bar {
        const int b = 5;   // default member initialization
        Bar(int c):b(c) {} // b is initialized with c
        Bar() {}           // b is initialized with 5
    };
    

提交回复
热议问题