Skip to content

Instantly share code, notes, and snippets.

@sy6sy2
Last active June 10, 2020 10:33
Show Gist options
  • Select an option

  • Save sy6sy2/f37177ea461d04d586dff700078262fa to your computer and use it in GitHub Desktop.

Select an option

Save sy6sy2/f37177ea461d04d586dff700078262fa to your computer and use it in GitHub Desktop.
[C++ const keyword] #CPP

C++ const keyword

Use const whenever possible.

Constant variable

If you make any variable as constant, using const keyword, you cannot change its value. Also, the constant variables must be initialized while they are declared.

Pointer with const keyword

Tip: always read types from right to left

Pointer to a const variable

This means that the pointer is pointing to a const variable (e.g. const int* p; or int const* p). p is apointer to a variable of type int which is const: The object of type int cannot be modified with p.

const pointer

int x = 1;
int* const w = &x;

Here, w is a pointer, which is const, that points to an int. Now we can't change the pointer, which means it will always point to the variable x but can change the value that it points to, by changing the value of x.

const pointer to a const variable

We can also have a const pointer pointing to a const variable (e.g. const int* const x;).

Defining class member variables as const

They are not initialized during declaration. Their initialization is done in the constructor. And once initialized, its value cannot be changed.

Defining class object as const

When an object is declared or created using the const keyword, its member variables can never be changed, during the object's lifetime.

Defining class's member function as const

A const member function never modifies member variables in an object (syntax: return_type function_name() const;).

mutable keyword

mutable keyword is used with member variables of class, which we want to change even if the object is of const type. Hence, mutable data members of a const objects can be modified.

Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment