Skip to main content

Lesson 3 of 7

const Member Functions & const-Correctness

A **const member function** (`void f() const`) promises not to modify the object - it receives `const Object*` as `this`. You should mark every member function const that doesn't need to modify the object. `mutable` allows specific members to be modified even in const contexts (used for caches and mutexes). **const-correctness** is the discipline of marking everything `const` that can be - it prevents bugs and enables the compiler to make better optimisations.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

const Methods, mutable & const-Correct API Design

const Methods, mutable & const-Correct API Design
#include <iostream>
#include <string>
#include <vector>
#include <optional>

class Matrix {
    std::vector<std::vector<double>> data_;
    int rows_, cols_;
    mutable bool cached_det_valid_ = false;  // mutable: modifiable in const
    mutable double cached_det_     = 0.0;

public:
    Matrix(int rows, int cols, double init = 0.0)
        : data_(rows, std::vector<double>(cols, init))
        , rows_(rows), cols_(cols)
    {}

    // ── const getter - does not modify object ────────────────
    int rows() const { return rows_; }
    int cols() const { return cols_; }

    // ── const element access - returns const ref ─────────────
    const double& at(int r, int c) const {
        return data_.at(r).at(c);  // .at() does bounds checking
    }

    // ── non-const element access - returns mutable ref ───────
    double& at(int r, int c) {
        cached_det_valid_ = false;  // invalidate cache on write
        return data_.at(r).at(c);
    }

    // ── const method using mutable cache ─────────────────────
    // Expensive but const: uses mutable to cache result
    double determinant() const {
        if (cached_det_valid_) {
            std::cout << "[cache hit] ";
            return cached_det_;
        }
        // simplified 2x2 det
        cached_det_       = (rows_ == 2 && cols_ == 2)
                            ? data_[0][0]*data_[1][1] - data_[0][1]*data_[1][0]
                            : 0.0;
        cached_det_valid_ = true;
        return cached_det_;
    }

    void print() const {
        for (const auto& row : data_) {
            for (const auto& v : row) std::cout << v << " ";
            std::cout << "
";
        }
    }
};

// ── const-correct function signatures ────────────────────────
// WRONG: void process(Matrix m)          - copies entire matrix
// WRONG: void process(Matrix& m)         - suggests mutation
// RIGHT: void process(const Matrix& m)   - read-only, no copy
void process(const Matrix& m) {
    std::cout << "Matrix " << m.rows() << "x" << m.cols() << "
";
    std::cout << "Det: " << m.determinant() << "
";  // const method OK
    // m.at(0,0) = 5;  ← compile error: returns const& on a const object
}

int main() {
    Matrix m{2, 2};
    m.at(0, 0) = 4; m.at(0, 1) = 3;
    m.at(1, 0) = 6; m.at(1, 1) = 3;
    m.print();

    process(m);                     // Det: -6
    std::cout << m.determinant();   // [cache hit] -6
    std::cout << "
";

    m.at(0,0) = 1;                  // invalidates cache
    std::cout << m.determinant();   // recomputed: 1*3 - 3*6 = -15
    std::cout << "
";

    return 0;
}

Common Mistakes

  • Not marking getters as const - `int size() { return size_; }` without `const` cannot be called on a `const MyClass&` parameter. Missing `const` on getters breaks const-correct code everywhere.
  • `mutable` misuse - `mutable` is for caches, mutexes, and lazy evaluation - things that change the implementation but not the observable state. Using `mutable` for actual state mutations defeats the purpose of const.
  • Returning non-const reference to private data - `std::string& name()` returns a mutable reference to a private member, letting callers bypass all validation. Prefer `const std::string& name() const` or return by value for small types.

Tip

Tip

Practice const Member Functions constCorrectness in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Guaranteeing Immutability Contract, Read-Only Method Access, and mutable Backdoors

Practice Task

Note

Practice Task - (1) Write a working example of const Member Functions constCorrectness from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with const Member Functions constCorrectness is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • A **const member function** (`void f() const`) promises not to modify the object - it receives `const Object*` as `this`.
  • Not marking getters as const - `int size() { return size_; }` without `const` cannot be called on a `const MyClass&` parameter. Missing `const` on getters breaks const-correct code everywhere.
  • `mutable` misuse - `mutable` is for caches, mutexes, and lazy evaluation - things that change the implementation but not the observable state. Using `mutable` for actual state mutations defeats the purpose of const.
  • Returning non-const reference to private data - `std::string& name()` returns a mutable reference to a private member, letting callers bypass all validation. Prefer `const std::string& name() const` or return by value for small types.

Topics in This Module

0/7 done