Skip to main content

Const Correctness as Design

intermediate20 min readLesson 70 of 204

const as an encoded promise: the const ladder, const member functions, and starting-maximal discipline.

const is a promise you encode in the type system: this thing will not be modified. Applied consistently it documents intent, lets the compiler catch bugs, and unlocks read-only APIs.

#include <string>
#include <vector>

long total(const std::vector<long>& prices) {   // promise: no mutation
    long sum = 0;
    for (const long& p : prices) sum += p;
    return sum;
}

class Cart {
public:
    long total() const { return total_; }        // const member: read-only view
    void add(long cents) { total_ += cents; }    // non-const: mutates
private:
    long total_{0};
};

The const ladder

  • const T& parameter โ€” cheap read-only input.
  • T get() const โ€” a member function that does not mutate (const after )).
  • const local โ€” write once, never again; intent made explicit.
  • constexpr (Module 7) โ€” computable at compile time.

How to think about it

Start maximal: make everything const. Removing const when you genuinely need mutation is easy and safe; adding it back across a codebase never is. Const on a member function is part of the interface contract โ€” callers can rely on it, and only a mutable member (rare, for caches/mutexes) may change inside one.

Now practice

Design a const-correct typeBuild a small type whose read-only API is enforced by const.1 challenge ยท ยท ~20 min