const
keyword
The const
declaration creates a read-only reference to a value.
We can use it in C, C++, JavaScript and Julia.
In CS247, we saw how there are 2 types of const
:
- Physical constness is about a particular object’s implementation. Compiler guarantees this for const objects/const refs. Ensures the fields won’t change.
- Logical constness asks not only for the fields to be immutable, but also that the memory associated with the representation of the ADT doesn’t change.
Logical constness is much stronger. There are parallels about physical copies and logical copies, see Shallow Copy and Deep Copy.
Resources
Different Types of Const
- Constant variables:
- Constant function parameters:
- Constant member functions in classes
- Constant return value (though in this example not useful)
Notice the difference
There is a difference depending on where you put the
const
keyword.
Taking the const
pledge(aka assuring const
correctness)
This means that you are promising not to change any of the subparts of the object
- For subparts that are objects (i.e., not ptrs), the meaning is obvious: You can’t change the sub-parts!
- NOTE: If the subpart is a pointer, you can’t change the pointer to point to a different object
- However, you are allowed to change the subparts of any object you point to, including calling non-const methods
const
pointers
https://www.internalpointers.com/post/constant-pointers-vs-pointer-constants-c-and-c