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?
struct Bar { const int b = 5; // default member initialization Bar(int c):b(c) {} }; Bar *b = new Bar(2); // Problem: Bar::b is modified to 2 // was expecting it to be an error
Any ideas?
In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization.
A constructor can initialize an object that has been declared as const , volatile or const volatile .
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant. The semantics of const in C are always of the first type.
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With