Advertisement

Const Correctness interview questions and answers

12 Const Correctness interview questions for C++ roles, each with a model answer, examples and likely follow-ups.

12 questions
Advertisement

12 questions

Q11 Intermediate Save

Why is const correctness important in API design?

const correctness makes interfaces self-documenting (which parameters and methods modify state), lets const objects be used freely, enables the compiler to catch accidental mutations, supports thread-safety reasoning (const often implies read-only), and is required to interoperate cleanly with const objects and references. Retrofitting const later is hard, so it's designed in from the start.
Real-world example
A well-const-qualified API lets callers pass const objects and reason about which calls are read-only.
Likely follow-ups
  • How does const aid thread-safety reasoning? | Why design const in from the start?
Const Correctness OOP & Classes
Q12 Advanced Save

What is the relationship between const and thread safety?

In modern C++, const on member functions is expected to be thread-safe for concurrent reads: the standard library assumes const operations can be called concurrently. This means a const method that mutates a mutable member (e.g., a cache) must synchronize (e.g., with a mutex) to remain safe. So const signals 'safe to call concurrently', which imposes obligations on mutable state.
mutable std::mutex m;
int get() const { std::lock_guard lk(m); return compute(); }
Real-world example
A const accessor that lazily caches must lock a mutable mutex to be safe for concurrent callers.
Likely follow-ups
  • What does const imply for concurrency? | What must mutable members do under const?
Concurrency Const Correctness

Showing 11–12 of 12