Const correctness provides two notable advantages to C++ that I can think of, one of which makes it rather unique.
- It allows pervasive notions of mutable/immutable data without requiring a bunch of interfaces. Individual methods can be annotated as to whether or not they can be run on const objects, and the compiler enforces this. Yes, it can be a hassle sometimes, but if you use it consistently and don’t use
const_castyou have compiler-checked safety with regards to mutable vs. immutable data.
- If an object or data item is
const, the compiler is free to place it in read-only memory. This can particularly matter in embedded systems. C++ supports this; few other languages do. This also means that, in the general case, you cannot safely cast
constaway, although in practice you can do so in most environments.
C++ isn’t the only language with const correctness or something like it. OCaml and Standard ML have a similar concept with different terminology — almost all data is immutable (const), and when you want something to be mutable you use a different type (a
ref type) to accomplish that. So it’s just unique to C++ within its neighboring languages.
Finally, coming the other direction: there have been times I have wanted const in Java.
final sometimes doesn’t go far enough as far as creating plainly immutable data (especially immutable views of mutable data), and don’t want to create interfaces. Look at the Unmodifiable collection support in the Java API and the fact that it only checks at run time whether modification is allowed for an example of why const is useful (or at least the interface structure should be deepend to have List and MutableList) — there is no reason that attempting to mutate an immutable structure can’t be a compile-type error.