Why use const?
My take is that you should try to use const
as much as you can. Mutable values are always a source of errors. You can avoid these errors by avoiding mutable values.
Function of const in C++
const
is used a lot because it has a lot off different meanings:
If we look at this signature, we can see two types of const bool operator ()(type const& a, type const& b) const {...}
: There is a const reference const &a
and const &b
, which just means that you cannot modify a
or b
, which you passed as reference.
There is also the const at the end of the method, which means that this method does not modify the instance. Figure a get-method. This method will not modify the instance it gets the value from. You can signal this to the caller by using T get_element(int at_index) const {...}
.
There are further const pointers.
Here you could change the value in the address, but not the address itself:
int *const a = new int;
*a = 1; // legal
a = &var; // illegal
Here you can change the address the pointer is pointing to, but not the value in that address.
const int *a = new int;
*a = 1; // illegal
a = &var; // legal
(Hope I did not confuse the two)
Have a pointer that does not allow any change:
const int * const a = new int;
*a = 1; // illegal
a = &var; // illegal
Further reading:
When to use constant pointers instead of const references.
YT - Const in C++
There is furthermore constexpr, which can calculate a value at compile time. This is different than the const
keyword, and might confuse you at the beginning.