Skip to main content

Task of const keyword

Short answer

The const keyword declares an entity as read-only after initialization, preventing modification. It applies to variables, pointers, function arguments, member functions, and objects, ensuring compile-time safety against unintended changes.

What is the task of const keyword?

The const keyword declares that a value cannot be modified after initialisation. Any attempt to change it gives a compile-time error.

Uses:

  1. Constant variable - replaces #define and is type safe: const float PI = 3.14159;
  2. Pointer to constant - the data cannot change through the pointer: const int *p;
  3. Constant pointer - the pointer cannot point elsewhere: int *const p = &x;
  4. Constant function argument - protects the argument: void show(const int &x);
  5. Constant member function - promises not to change the object's data: int getX() const { return x; }
  6. Constant object - can call only const member functions.
const int MAX = 100;
// MAX = 200;   // error: assignment of read-only variable

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 2 questions →