ProgrammingC++ Developer

How does const-correctness work in C++? Why is it important to use const qualifiers, and what errors does const-correctness help avoid? Provide a real example of using const in methods and functions.

Pass interviews with Hintsage AI assistant

Answer.

const-correctness is a concept in C++ that defines how variables, pointers, references, and methods are marked as "read-only". It enhances code safety, makes class interfaces clearer, and allows the compiler to catch errors at compile-time rather than at runtime.

Using const qualifiers is important because:

  • It explicitly distinguishes which methods and functions do not modify the object/data.
  • It prevents accidental modification of data that should not change.
  • It helps the compiler optimize code.

Example:

class MyArray { public: int getItem(size_t idx) const { // Does not modify the object return arr[idx]; } void setItem(size_t idx, int value) { arr[idx] = value; } private: int arr[10]; };

Here, the getItem method ensures that it does not modify the object.

Trick Question.

What is the difference between

void foo(const int* ptr);

and

void foo(int* const ptr);

?

Correct answer:

  • const int* ptr — a pointer to a constant value, the value cannot be changed, the pointer can.
  • int* const ptr — a constant pointer to a mutable value, the pointer cannot be changed, the value can.

Examples of real errors due to ignorance of the subtleties of the topic.


Story
In a large project, a class method was written without a const qualifier:

int MyClass::getVal();

Because of this, it was impossible to use the class object as a const reference, for example, in functions that work only with "read-only" objects. This limited code reuse and led to excessive object copying.


Story
A developer mistakenly returned a reference to internal data through a non-const method:

int& MyClass::getInt();

As a result, client code gained the ability to modify a private field of the class, leading to unexpected state changes and hard-to-trace bugs.


Story
Leaving a constant parameter without const in a function:

void printVector(std::vector<int>& v);

someone accidentally modified the vector right in the function for debugging, forgetting to remove that code. This caused a side-effect, almost unnoticed in tests, and was only discovered in production.