Your definition is at odds with C++ (one of the most widely used languages of all time), and its use of `const`.
C++'s const is your "immutability".
C++'s const is your "immutability".
struct X {
const int i{123};
const int j;
X(int j_) : j{j_} {}
};
// non-const object; x.i == 123; x.j == 111
X x{111};
x.i = 222; // compilation error
x.j = 333; // compilation error struct X {
X(Y val) : y_{val} {}
// Can be called on const and non-const X objects
const Y& y() const { return y_; }
// Can only be called on non-const X objects
Y& y() { return y_; }
private:
Y y_;
};
void f(X& x) { x.y() = 222; }
void g(const X& x) { x.y() = 222); }
const X x{123}; // x.y() == 123
x.y() = 222; // compilation error
f(x); // compilation error (f's parm is non-const)
g(x); // compilation error (can't assign to const ref)
// Cannot take non-const ref or ptr of x
X& xr{x}; // compilation error
X* xp{&x}; // compilation error
If the original declaration of the variable is const nothing can modify it. (And as my first example shows, the original declaration can always be const if you want it to be, regardless of context.) You can't take a non-const pointer or reference to x without explicitly circumventing the language like this: X& xr{const_cast<X&>(x)};
X* xp(const_cast<X*>(&x)};So, a const value cannot be mutated locally or globally. So if you make something const and expose it, it cannot be changed.