const correctness
What you will learn on this page
Section titled “What you will learn on this page”- What
constmeans on variables, parameters, member functions, and return types. - How
constturns a design’s “read-only” promises into compile errors when they are broken. - Why casting
constaway is almost always a design mistake. - The difference between logical and bitwise constness, and when
mutableis acceptable.
const is a promise the compiler checks
Section titled “const is a promise the compiler checks”const marks something as read-only. Written in the right places, it lets
an interface say which operations change an object and which only look at it,
and the compiler enforces that statement everywhere the interface is used. Using
const consistently, everywhere it applies, is called
const correctness.
The main places it appears:
IllustrativeA fragment for explanation; not compiled on its own.
const int limit = 5; // a variable that cannot changevoid print_report(const Catalog& catalog); // the function only reads catalogint total_copies() const; // calling it does not change *thisconst CatalogEntry* find(std::string_view) const; // the caller may read, not write- A
constvariable cannot be changed after it is initialized. - A
const¶meter lets a function read the caller’s object without copying it and without changing it (see the previous lesson). - A
constmember function, withconstafter the parameter list, promises not to change the object it is called on. It is the only kind of member function that can be called on aconstobject or through aconst&. - A pointer or reference to
constin a return type gives the caller read-only access to something inside the object.
A const-correct catalog
Section titled “A const-correct catalog”A library catalog holds entries, and one rule matters: no two entries have the same ISBN, and no entry has a negative number of copies.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The library's list of books. Each CatalogEntry (defined above) holds an// ISBN, a title, and a number of copies. The functions that change the// catalog (add, set_copies) are not const; the ones that only look at it// (find, size, total_copies) are const, so a caller holding a// const Catalog& can use those and nothing else.// Invariant: ISBNs are unique and copies >= 0 for every entry.class Catalog {public: // Adds a new entry. `entry` is taken by value: the catalog keeps its own // copy, moved in (see catalog.cpp). // Returns false, and changes nothing, if the ISBN is already present or // copies is negative. bool add(CatalogEntry entry); // Changes the number of copies of one existing entry; the only way a // caller can change an entry after adding it. std::string_view is a // cheap read-only view of some text, so a string literal or a // std::string can be passed without copying it. // Returns false if no entry has this ISBN or copies is negative. bool set_copies(std::string_view isbn, int copies);
// Read-only view of one entry, or nullptr. The caller cannot change the // entry through it, so the ISBN stays unique. // `const CatalogEntry*` reads "pointer to a const CatalogEntry": the // caller may read entry->title but not assign to it. nullptr is the // "no such entry" answer. The pointer points into the catalog's own // vector, so it stops being valid after a successful add (which may // move every entry to new memory) or when the catalog is destroyed. [[nodiscard]] const CatalogEntry* find(std::string_view isbn) const; [[nodiscard]] std::size_t size() const noexcept { return entries_.size(); } // Logically const: computes the total once and caches it. // The sum of `copies` over every entry. The caller cannot tell whether // the answer was computed now or remembered from last time, so the // function counts as not changing the catalog, and is marked const. [[nodiscard]] int total_copies() const;
private: std::vector<CatalogEntry> entries_; // Not part of the observable state; cleared whenever entries_ changes. // std::optional<int> is either empty ("no total worked out yet") or // holds the last total. `mutable` lets a const member function, here // total_copies, assign to it anyway. mutable std::optional<int> total_cache_;};Look at which functions are const. add and set_copies change the catalog, so
they are not. find, size, and total_copies only report on it, so they are.
The header alone tells a reader which operations are safe to call on a catalog
they were given to read.
Now look at the return type of find: const CatalogEntry*. Read it as
“pointer to a const CatalogEntry”: the entry cannot be changed through this
pointer. (CatalogEntry* const would be the reverse: a pointer that cannot be
re-pointed, to an entry that can be changed.) find returns nullptr when the
ISBN is absent. This matters for the
invariant. If find returned a plain CatalogEntry*, any caller could write
catalog.find("isbn-2")->isbn = "isbn-1"; and break the uniqueness rule from
outside, exactly the problem private data was meant to solve in the classes
lesson. Returning a pointer to const keeps the entries readable but not
writable, and the one legitimate change, the number of copies, goes through
set_copies, which checks the rule.
A function that takes the catalog by const& can call only the const members:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Takes the catalog by const reference: it can only call const functions.// size, total_copies, and find are all const, so every call compiles.void print_report(const Catalog& catalog) { std::cout << catalog.size() << " titles, " << catalog.total_copies() << " copies\n"; // Declare a variable inside the `if` and test it at once: a pointer // counts as true when it is not nullptr. So the body runs only if the // ISBN was found, and `entry` is visible only inside the if. if (const CatalogEntry* entry = catalog.find("978-0201485677")) { // `entry->title` reads a member through a pointer; read-only here. std::cout << " found: " << entry->title << '\n'; }}If print_report tried to call catalog.add(...), the program would not compile.
Here it is in use:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each brace list builds a CatalogEntry: isbn, title, copies.Catalog catalog;catalog.add({"978-0201485677", "Refactoring", 2});catalog.add({"978-0321125217", "Domain-Driven Design", 1});// Same ISBN as Refactoring, so add refuses it and returns false.std::cout << "duplicate added: " << catalog.add({"978-0201485677", "Copy", 1}) << '\n';print_report(catalog); // 2 titles, 3 copies (2 + 1)
// The one allowed change to an entry. It also empties the cached total.catalog.set_copies("978-0321125217", 4);print_report(catalog); // 2 titles, 6 copies (2 + 4): recomputedduplicate added: false2 titles, 3 copies found: Refactoring2 titles, 6 copies found: RefactoringThe implementation:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Check both rules first, then change. `find(...) != nullptr` means "an// entry with this ISBN already exists". A non-const function such as add// may call the const function find. std::move hands the entry's strings to// the new vector element instead of copying them. Then the cached total is// thrown away (reset() empties the optional), because it may now be wrong.bool Catalog::add(CatalogEntry entry) { if (entry.copies < 0 || find(entry.isbn) != nullptr) return false; entries_.push_back(std::move(entry)); total_cache_.reset(); return true;}
bool Catalog::set_copies(std::string_view isbn, int copies) { if (copies < 0) return false; // Searches again rather than const_cast-ing the result of find(). // std::find_if walks from begin() to end() and stops at the first // element for which the lambda returns true. The lambda's [isbn] copies // the view into the lambda (cheap: a view is just a pointer and a // length) so its body can compare against it. The result `it` is an // iterator: a position in the vector that can be used to reach and // change that element. Here `auto` stands for the vector's iterator type. auto it = std::find_if(entries_.begin(), entries_.end(), [isbn](const CatalogEntry& e) { return e.isbn == isbn; }); if (it == entries_.end()) return false; // end() means "not found" it->copies = copies; // `it->` reaches the element, like a pointer total_cache_.reset(); // the total depends on copies, so forget it return true;}
// A const function, so `entries_` is const in here: the loop variable can// be a const reference (a plain CatalogEntry& would not compile). Because// it is a reference, not a copy, &entry is the address of the element// inside the vector, returned as a pointer to const.const CatalogEntry* Catalog::find(std::string_view isbn) const { for (const CatalogEntry& entry : entries_) { if (entry.isbn == isbn) return &entry; // first match: stop looking } return nullptr; // looked at every entry: none has this ISBN}
// Compute on the first call, remember, and answer from memory until a// change empties the cache. `!total_cache_` is true when the optional is// empty. `*total_cache_` reads the int stored inside it.int Catalog::total_copies() const { if (!total_cache_) { int total = 0; for (const CatalogEntry& entry : entries_) total += entry.copies; total_cache_ = total; // allowed in a const function: the member is mutable } return *total_cache_;}How this code works: the catalog and its cached total
Follow entries_ and the cache total_cache_ through the usage code above.
| Step | Result | Entries (copies) | total_cache_ after |
|---|---|---|---|
add Refactoring, 2 |
true |
Refactoring 2 | empty |
add Domain-Driven Design (DDD), 1 |
true |
Refactoring 2, DDD 1 | empty |
add “Copy” with Refactoring’s ISBN |
false |
unchanged | empty |
print_report: total_copies() |
3 | unchanged | 3 |
set_copies DDD to 4 |
true |
Refactoring 2, DDD 4 | empty |
print_report: total_copies() |
6 | unchanged | 6 |
addchecks before it changes. The duplicate is refused at the first line, becausefindfinds the existing Refactoring entry, so nothing is pushed and the cache is not touched.total_copiesfinds the cache empty on its first call, adds up the copies (2 + 1), stores 3 in the cache, and returns it. A second call before any change would skip the loop and return the stored 3.set_copiesfinds the entry withstd::find_if, writes the new count through the iterator, and empties the cache. That reset is what makes the second report say 6 and not a stale 3.findreturns the address of the matching element, typed as a pointer toconst.print_reportuses it to read the title; it could not assign toentry->titleeven if it wanted to.
add calls find, which is allowed: a non-const member function may call
const ones. The reverse is not allowed: inside a const member function,
this points to a const Catalog, so only const members can be called and
data members cannot be assigned, with one exception explained next.
Logical constness and mutable
Section titled “Logical constness and mutable”total_copies is const, yet it writes total_cache_. That is allowed because
total_cache_ is declared mutable, which exempts a member from the const
rules.
This is the difference between two meanings of “does not change the object”:
- Bitwise constness: the function does not change the object’s own data
members. This is what the compiler checks by default: inside a
constmember function, assigning to a (non-mutable) member is an error. The check is shallow: if a member is a pointer, the data it points to can still be changed. - Logical constness: nothing a caller can observe through the public interface changes. Caching a computed result is invisible to callers: they get the same answer either way, only faster the second time.
const in an interface should mean logical constness. mutable is the tool for
the rare members that are not part of the observable state, such as a cache. It
comes with two obligations, both visible in the example:
- Every change to the real state must invalidate the cache.
addandset_copiesboth calltotal_cache_.reset(). Forget one, andtotal_copiesreturns a stale total. The testcached_total_follows_changeschecks this. - A
mutablemember breaks the usual promise about threads. Code often assumes that callingconstfunctions from several threads at once is safe, because nothing is written. With amutablecache, two threads can writetotal_cache_at the same time, which is a data race. The header comment says so; a version meant for threads would protect the cache with a mutex (covered in the concurrency lessons) or not cache at all.
The flawed shortcut: casting const away
Section titled “The flawed shortcut: casting const away”const_cast can remove const from a pointer or reference. Here someone wanted
to change an entry and found that find gives only read-only access:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// The signature promises "I only read the catalog" (const Catalog&). The// body breaks that promise. In this program the catalog already holds// "isbn-1" and "isbn-2", and total_copies() has been called, so the cached// total (3) is filled in.void quick_fix(const Catalog& catalog) { // "find() only gives me a const pointer, so I'll cast the const away." // catalog.find returns const CatalogEntry*. const_cast<CatalogEntry*> // produces the same address with the read-only promise removed, so the // compiler now allows writes through it. It does not copy the entry: // `entry` points straight at the element inside the catalog's vector. auto* entry = const_cast<CatalogEntry*>(catalog.find("isbn-2")); if (entry != nullptr) { // Each write goes around the class's checks. add() would have // refused a duplicate ISBN, and set_copies() would have reset the // cache; neither runs here. entry->isbn = "isbn-1"; // now two entries share an ISBN entry->copies = 10; // and total_copies() still returns the old total }}This compiles. It also breaks every promise the catalog makes:
- Two entries now have the ISBN
isbn-1, so the uniqueness invariant is broken.find("isbn-1")returns whichever comes first, and the other entry can no longer be found by its ISBN. - The cached total was not reset, because the change bypassed
set_copies. The program’smain(not shown) callstotal_copies()beforequick_fix, so afterwards it still returns the old total. - The function’s own signature,
const Catalog&, told every caller “I only read”. It lied.
There is a worse case. If the object being written was itself defined
const (for example, const CatalogEntry entry{"isbn-9", "Emma", 1};), writing
to it through a cast has undefined behaviour: the compiler may assume a const
object never changes, and may even place it in read-only memory. Here the
entries are elements of the catalog’s std::vector, which are not const
objects, so the write is not undefined behaviour, but it still breaks the design.
const_cast is safe only when the object really is not const, and a function
that receives a const& has no way to know that.
The fix is not a cleverer cast. If callers need to change entries, the class
should offer an operation that keeps the rule, as set_copies does. A
const_cast in application code almost always means the design is missing an
operation.
Testing the contract
Section titled “Testing the contract”The tests check the invariant and the cache. The last line uses static_assert
to check, at compile time, that find returns a pointer to const, so a future
change that made it writable would fail the build.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST, LLD_CHECK, and LLD_CHECK_EQ come from the site's test header,// lld_test.hpp (explained with the first lesson's tests).
// Both halves of the invariant: a second "isbn-1" and a negative count// are each refused, so only the first entry is in the catalog.LLD_TEST(rejects_duplicate_isbn_and_negative_copies) { Catalog catalog; LLD_CHECK(catalog.add({"isbn-1", "Refactoring", 2})); LLD_CHECK(!catalog.add({"isbn-1", "Another", 1})); LLD_CHECK(!catalog.add({"isbn-2", "Negative", -1})); LLD_CHECK_EQ(catalog.size(), std::size_t{1});}
// The cache's obligation: after every kind of change (add, set_copies)// the total must be recomputed, not the stale one returned. Each// total_copies() call after a change would give the old number if that// change forgot to reset the cache.LLD_TEST(cached_total_follows_changes) { Catalog catalog; catalog.add({"isbn-1", "Refactoring", 2}); LLD_CHECK_EQ(catalog.total_copies(), 2); // fills the cache catalog.add({"isbn-2", "Domain-Driven Design", 3}); LLD_CHECK_EQ(catalog.total_copies(), 5); LLD_CHECK(catalog.set_copies("isbn-1", 0)); LLD_CHECK_EQ(catalog.total_copies(), 3);}
// find gives a pointer to the stored entry when the ISBN exists, and// nullptr when it does not.LLD_TEST(find_returns_read_only_entry_or_null) { Catalog catalog; catalog.add({"isbn-1", "Refactoring", 2}); const CatalogEntry* entry = catalog.find("isbn-1"); LLD_CHECK(entry != nullptr); LLD_CHECK_EQ(entry->title, std::string("Refactoring")); LLD_CHECK(catalog.find("missing") == nullptr);}
// The compiler enforces the contract: find() gives read-only access.// Read it inside out. std::declval<Catalog&>() pretends to have a// (non-const) Catalog, without making one; .find("") is a call on it;// decltype(...) is the type that call would return, worked out at compile// time without running anything. std::is_same_v checks that type is exactly// const CatalogEntry*. If someone changed find to return a writable// CatalogEntry*, this line would stop the build.static_assert(std::is_same_v<decltype(std::declval<Catalog&>().find("")), const CatalogEntry*>);When to use const, and when not
Section titled “When to use const, and when not”Use const:
- on every member function that does not change the object’s observable state;
- on reference and pointer parameters the function only reads;
- on local variables that are not meant to change after initialization, which makes the code easier to read;
- on returned references and pointers into an object’s internals, unless callers are meant to modify them.
Do not use const:
- on by-value parameters in a declaration:
void f(const int n);means nothing to the caller, who passes a copy anyway. (Inside a function definition it is harmless, and some teams use it to stop the body from changing the parameter.) - on by-value return types:
const std::string name() const;prevents the caller from moving the result, which costs performance for no benefit. - on data members of a class you want to copy-assign: a
constmember disables assignment of the whole object. To make a member unchangeable, keep it private and provide no setter.
Common mistakes
Section titled “Common mistakes”- Forgetting
conston a read-only member function. Callers holding aconst&cannot call it, and they are tempted to dropconsteverywhere, or to cast it away. - Returning a non-const pointer or reference into private data. It lets callers bypass the class’s rules.
const_castto work around a missing operation. Add the operation instead.mutablefor real state. If a caller could notice the change, the function is not logicallyconst, so do not mark itconst.- A
mutablecache without invalidation. Every function that changes the real state must clear it. - Assuming
constmeans thread-safe. Callingconstfunctions from several threads at once is safe only if none of them writes amutablemember, or data behind a pointer, without synchronization.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Librarians can correct a misspelled title.”
The tempting change is to make find return a non-const pointer so callers can
edit the title. That reopens every field, including the ISBN. The const-correct
change adds one operation, bool rename(std::string_view isbn, std::string title),
that changes only the title and rejects an empty one. It is not const, because
it changes the catalog. It does not touch total_cache_, because a title does not
affect the total; the comment on the cache should say which members it depends on,
so the next person adding an operation knows whether to reset it.
Exercise: Make an interface const-correct
This interface for a member’s account compiles, but it is not const-correct. Fix it, and explain each change.
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
class MemberAccount {public: std::string& name(); // returns the member's name int loans_held(); // number of loans held now bool can_borrow(); // true if under the loan limit void add_loan(Loan& loan); // records a new loan (copies it) std::vector<Loan> loans(); // all current loans const int max_loans(); // the limit};Show the explained answer
IllustrativeA fragment for explanation; not compiled on its own.
class MemberAccount {public: const std::string& name() const; // read-only access, query int loans_held() const; // query bool can_borrow() const; // query void add_loan(const Loan& loan); // reads the loan, stores a copy const std::vector<Loan>& loans() const; // read-only view, no copy int max_loans() const; // query; no const on the value};name()returnedstd::string&, so callers could rename the member by writing through it, bypassing any rule. It now returnsconst std::string&and is aconstmember function. (If renaming is needed, add arenameoperation that checks the new name.)loans_held(),can_borrow(), andmax_loans()only report on the account, so they areconst. Without that, no code holding aconst MemberAccount&could ask whether the member may borrow.add_loan(Loan&)took a non-const reference although it only copies the loan. That misleads readers (“will it change my loan?”) and rejects temporaries such asaccount.add_loan(Loan{...}).const Loan&fixes both. TakingLoanby value and moving it in, as in the previous lesson’s sink parameter, is an equally good answer.loans()returned a copy of the whole vector on every call. Returningconst std::vector<Loan>&gives read-only access without copying. The cost is a lifetime rule: the reference is valid only while the account is alive and unchanged, which the header comment must state. Returning by value is also defensible if callers usually keep the result.const int max_loans():conston a by-value return type does nothing useful; theconstthat matters is the one after the parentheses.
Summary
Section titled “Summary”constturns “this only reads” into a rule the compiler checks at every call.- Mark every member function that does not change observable state
const, and take read-only parameters byconst&. - Return pointers or references to
constso callers cannot bypass the class’s rules. const_castto modify an object breaks the design’s promises, and is undefined behaviour if the object was definedconst. Add the missing operation instead.constmeans logical constness;mutableis for unobservable members such as caches, which must be invalidated on every change and are not thread-safe by themselves.