Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 171 ยท Object-Oriented Programming

const Member Functions and mutable

Learn C++ const member functions - const objects, why getters must be const, const overloading of operator[], mutable caches, and const-correctness pitfalls.

When you pass an object by const reference, you are promising the caller that your function will only look at it. The compiler holds you to that promise, but it needs help: it can't read the body of every member function to decide whether it changes the object. So C++ asks the class author to label each member function that doesn't modify the object with the keyword const after the parameter list.

That small keyword decides which functions you may call on const objects, const references and const pointers. Forget it, and your class becomes almost unusable in real code, because real code passes objects around as const T& all the time. In this lesson you'll learn how const member functions work, what they may and may not do, how to overload on const (the trick behind std::vector::operator[]), and when the mutable keyword is the honest answer.

The problem: calling methods on a const object

Here is a small class whose author forgot about const. Everything works until the object is passed by const reference.

C++
class Temperature {
public:
    explicit Temperature(double celsius) : celsius_{celsius} {}
    double celsius() { return celsius_; }          // not marked const
    void set_celsius(double c) { celsius_ = c; }
private:
    double celsius_;
};

void report(const Temperature& t) {
    std::println("{}", t.celsius());   // error: passing 'const Temperature' as 'this'
}                                      // argument discards qualifiers

GCC's message mentions this because, inside a member function, the object is reached through the hidden this pointer (see The this Pointer). In a normal member function of Temperature, this has type Temperature*. A const Temperature can't be pointed at by a plain Temperature*, because that pointer would allow changes. The call is rejected even though celsius() doesn't actually change anything.

Declaring a const member function

Put const after the parameter list. Inside that function, this becomes a const Temperature*, so every data member is treated as const.

C++ A const getter works on const objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The rules fit in one table:

Object you call through const member function non-const member function
Non-const object, T&, T* allowed allowed
const T object, const T&, const T* allowed compile error

A const member function can be called on anything. That's why the rule of thumb is simple: mark every member function const unless it must change the object. Getters, size(), empty(), to_string(), comparison operators and printing functions are almost always const.

When you define the function outside the class, the const is part of its signature and must be repeated:

C++
class Circle {
public:
    double area() const;     // declaration
private:
    double radius_ = 1.0;
};

double Circle::area() const {   // the definition repeats const
    return 3.14159 * radius_ * radius_;
}

Leaving const off the definition doesn't give you a warning; it declares a different function, and the linker or compiler then complains that Circle::area() doesn't exist.

What a const member function may not do

Inside a const member function, the compiler stops you from:

  • assigning to a data member (count_ = 0;),
  • calling a non-const member function on *this (clear();),
  • calling non-const functions on members (items_.push_back(x);),
  • returning a non-const reference or pointer to a member (return items_; as std::vector<int>&).

That last one is easy to miss. If a const function could hand out a T& to its insides, the caller could modify a const object through it, and the whole promise would be worthless. Returning a const T& is fine.

const is shallow for pointers

const protects the members themselves, not what they point to. If a member is a pointer, the pointer becomes const in a const function, but the object it points at does not:

C++ const protects the pointer, not the pointee

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This is legal, but think about what your class means. If the pointed-to data is logically part of the object (a buffer the class owns, for example), changing it in a const function breaks the spirit of const even though the compiler allows it. Smart pointers behave the same way: std::unique_ptr<T> is shallow too. Standard containers are deep: a const std::vector<int> doesn't let you change its elements, because the vector's own const overloads return const references.

Overloading on const

A member function can have two versions that differ only in const. The compiler picks the const one for const objects and the non-const one otherwise. This is exactly how std::vector::operator[], at(), front(), begin() and friends work: on a mutable vector they return a T& you can write through, and on a const vector they return const T&.

C++ const and non-const overloads of at()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both overloads have identical bodies here. When the body is long, people used to write the const version and have the non-const one call it with a const_cast on the result. C++23's explicit object parameter ("deducing this") removes the duplication properly: one template handles both cases.

C++
class Playlist {
public:
    // One function for both const and non-const objects (C++23).
    template <typename Self>
    auto&& at(this Self&& self, std::size_t i) {
        return std::forward<Self>(self).songs_.at(i);
    }
private:
    std::vector<std::string> songs_;
};

Self is deduced as Playlist&, const Playlist& or Playlist&&, and the return type follows. You'll understand std::forward fully after Move Semantics and Variadic Templates; for now, the two-overload version is perfectly fine.

Overloading on & and && (ref-qualifiers)

For completeness: just as const after the parameter list says "callable on const objects", & or && there say "callable only on lvalues" or "only on temporaries". std::optional::value() uses this so std::move(opt).value() can move the contents out. You'll rarely need it in your own classes.

Bitwise const vs logical const

The compiler enforces bitwise const: no member's bytes may change. But what users care about is logical const: the object's observable value doesn't change. Usually these agree. Sometimes they don't:

  • A class that caches an expensive result wants to fill the cache on the first const call.
  • A thread-safe class needs to lock a mutex inside const getters, and locking changes the mutex.
  • A class counts how often it was read, for statistics or debugging.

In each case the object's visible value stays the same, so the function should be const, yet a member changes. That's what mutable is for.

mutable: members that const doesn't cover

A data member declared mutable can be modified even inside const member functions and even in const objects. Use it only for members that are not part of the object's logical value.

C++ A mutable cache in a const function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Note the second half of the pattern: every non-const function that changes the real data must invalidate the cache. Forgetting that is the classic caching bug.

The other standard use is a mutable std::mutex:

C++
class Inventory {
public:
    int count(const std::string& item) const {
        std::scoped_lock lock{mutex_};          // locking modifies mutex_
        auto it = stock_.find(item);
        return it == stock_.end() ? 0 : it->second;
    }
private:
    mutable std::mutex mutex_;
    std::map<std::string, int> stock_;
};

You'll learn locks in Mutexes and Locks. One thing to know now: the standard library assumes that calling const member functions from several threads at once is safe. A mutable cache like the one in Document breaks that assumption if two threads call word_count() simultaneously. If your class is shared between threads, guard the cache with a mutex or an atomic.

mutable is not a "turn off const" switch. If you find yourself making the object's real data mutable so that a function can be const, the function shouldn't be const. Reserve mutable for caches, mutexes, counters and similar bookkeeping.

Lambdas use the same keyword with a related meaning: a lambda's call operator is const by default, and mutable lets it modify its by-value captures. See Lambda Expressions.

const-correctness habits

  • Mark member functions const by default. Adding const later is painful, because every function that calls it through a const& must already exist.
  • Return const T& or by value from const getters, never a plain T& to a member.
  • Don't return const by value (const std::string name() const;). It blocks moving from the result and buys nothing.
  • Don't cast const away to call a non-const function. Modifying an object that was defined const through a const_cast is undefined behavior.
  • const data members (const int id_;) make objects non-assignable, which breaks sorting and std::vector reassignment. Prefer a private non-const member with only a getter. See Copy Constructors and Copy Assignment.
  • static member functions can't be const: they have no this and no object. You'll see why in Static Members.

For const with plain pointers and references (const int* vs int* const), revisit const with Pointers and References.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given void show(const Box& b), which call inside show compiles?

    Through a const reference you can only call const member functions. A function without const after its parameter list is rejected even if it doesn't change anything.
  2. 2. A class has both int& get() and const int& get() const. What happens with const Widget w; w.get() = 5;?

    For a const object only the const overload is viable. It returns a const reference, and assigning through it is a compile error.
  3. 3. A class has a member int* data_;. Inside a const member function, which statement compiles?

    const is shallow. The pointer member itself becomes const (int* const), but the int it points to is not part of the object, so writing through it compiles.
  4. 4. Which member is a good candidate for mutable?

    mutable is for bookkeeping that doesn't affect the object's logical value, such as caches, mutexes and statistics counters. Real data like a balance or the elements must stay protected by const.

Summary

  • const after a member function's parameter list makes this a pointer to const; the function can't modify data members or call non-const members.
  • const objects, const T& and const T* can only call const member functions. Mark every function const unless it must change the object.
  • The const is part of the signature: repeat it in out-of-class definitions.
  • const is shallow for raw and smart pointer members; standard containers are deep.
  • Overloading on const lets accessors return T& for mutable objects and const T& for const ones; C++23 "deducing this" can merge the two.
  • mutable members may change in const functions. Use them for caches, mutexes and counters, invalidate caches when real data changes, and mind thread safety.

Next: Static Members, where you'll learn about data and functions that belong to the class itself rather than to any one object.