- const Type myVariable = initial; // Declares a const variable; cannot be changed
- const Type &myReference = myVariable; // Declares a reference to a const variable
- const Type *myPointer = &myVariable; // Declares a pointer-to-const. The pointer can change, but the underlying data member cannot be changed through the pointer
- Type * const myPointer = &myVariable; // Declares a const pointer. The pointer cannot be reassigned to point to something else, but the underlying data member can be changed
- const Type * const myPointer = &myVariable; // Declares a const pointer-to-const.
A variable marked as
const cannot1 be changed. Attempting to call any non-const operations on it will result in a compiler error.
1: Well, it can be changed through
const_cast, but you should almost never use that
Avoiding duplication of code in const and non-const getter methods.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0