C++ Const

less than 1 minute read

Const Memory

Changing the value of a const:

  • Storage for a const value may be changed by using pointers.
  • Compilers may choose to just replace occurances of the const with its value.
  • See http://cpp.sh/86yky for an example.
const int year = 2020;
int * time_machine;
time_machine = (int *)&year;
*time_machine = 2019;
const int *year_stored = &year;
std::cout << *year_stored << std::endl; // output: 2019
std::cout << year << std::endl; // output: 2020

Const pointers

Pointer to a const value (i.e. can’t change the value)

const int *ptr;
int const *ptr; // does the same as the line above

const pointer to a value (i.e. can’t change the pointer)

int * const ptr;

Const with Classes

const in class methods:

  • Indicates that class member variables won’t be modified in this method
class TimeMachine {
	int year;
	int get_year() const {
		return year;

// When accessing a reference of a class, we can only use the const methods
int my_age(const TimeMachine& time_machine) {
	// This is an error if get_year is not const
	return time_machine.get_year() - 1988;