In Object-oriented programming, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const
keyword in those languages.
The idea of const-ness does not imply that the variable as it is stored in the computer's memory is unwriteable. Rather, const
-ness is a compile-time construct that indicates what a programmer should do, not necessarily what they can do. Note, however, that in the case of predefined data (such as const char *
string literals), C const
is often unwritable.
In addition, a method can be declared as const
. In this case, the this
pointer inside such a method is of type const ThisClass* const
rather than of type ThisClass* const
. This means that non-const methods for this object cannot be called from inside such a method, nor can member variables be modified. In C++, a member variable can be declared as mutable
, indicating that this restriction does not apply to it. In some cases, this can be useful, for example with caching, reference counting, and data synchronization. In these cases, the logical meaning (state) of the object is unchanged, but the object is not physically constant since its bitwise representation may change.
Read more about Const-correctness: C++ Syntax, const
and immutable
in D, final
in Java, const
and readonly
in C#