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?
<
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
...