skip to content

Access and Const Correctness

public, protected and private, const member functions, mutable, static members and friends shape a class's interface. Interviewers ask what a const method may change.

on this pageshow

explore

questions

5

In C++, what does declaring a member function const promise, and what can its body still modify?

level: juniorimportance: must knowfreq 80%

answer

  1. the type of this changes
  2. pointer to const object
  3. only const members callable
  4. mutable, static, pointees exempt

basics

~20 s

Inside a const member function, this points to const: the body cannot assign ordinary members or call non-const member functions, and the function is callable on const objects. Mutable members, static members and data behind pointer members stay writable.

solid answer

~50 s

A trailing `const` changes the type of `this` from `Cache*` to `const Cache*`, so every non-static data member is treated as `const` inside the body. The body cannot assign those members or call member functions that are not themselves `const`, and the compiler enforces it. In exchange the function can be called on `const` objects and through `const Cache&`, which is how most read-only code receives objects. You can overload on it: `int& at(int)` for non-const objects and `const int& at(int) const` for const ones. Three things stay writable: members declared `mutable`, static data members (they are not part of the object), and anything reached through a pointer member, because constness applies to the pointer, not its pointee. Casting const away with `const_cast` compiles, but modifying an object that was defined `const` is undefined behaviour.

code

cpp · 25 lines
cpp
#include <cstdio>
#include <type_traits>
#include <vector>

class Cache {
public:
    int& at(int i) { return data_[i]; }               // chosen for non-const objects
    const int& at(int i) const { return data_[i]; }   // chosen for const objects
    int size() const {
        static_assert(std::is_same_v<decltype(this), const Cache*>);
        // data_.push_back(0);  // error: data_ is const in here
        return static_cast<int>(data_.size());
    }
    void clear() { data_.clear(); }
private:
    std::vector<int> data_{1, 2, 3};
};

int main() {
    Cache c;
    const Cache& view = c;
    c.at(0) = 10;                 // non-const overload
    std::printf("%d %d\n", view.at(0), view.size());
    // view.clear();              // error: clear() is not const
}

go deeper

for a junior

Recall that a const member function can be called on const objects and cannot assign ordinary members or call non-const member functions.

for a middle

Explain the mechanism: this becomes a pointer to const, which is why const overloads exist and why pointer members are only shallowly protected.

for a senior

Show where the guarantee leaks, through pointer members and const_cast, and why modifying an object defined const is undefined behaviour rather than a style issue.

for a principal

Frame const correctness as an API contract that callers and the standard library rely on, and decide how strictly a codebase enforces const on accessors and parameters.

## What the trailing const changes A **non-static member function** receives the object it is called on through the pointer `this`. Writing `const` after the parameter list changes the type of that pointer: the C++ standard says `this` is a prvalue of type "pointer to cv-qualifier-seq X", so in `int Cache::size() const` it has type `const Cache*`. Every consequence follows from that one type: - Each non-static data member, accessed through `this`, is a **const lvalue** in the body. - Only member functions that are themselves `const` can be called on `*this`. - The function can be called on a **const object**, a `const Cache&` or a `const Cache*`; a non-const member function cannot. This is enforced by the type system, not by convention. Uncommenting the two error lines in the code example makes Apple clang 21 print: ```plaintext constmf.cpp:11:15: error: no matching member function for call to 'push_back' constmf.cpp:24:5: error: 'this' argument to member function 'clear' has type 'const Cache', but function is not marked const ``` ## What the body may still change | Kind of state | Writable in a const member function? | Why | |---|---|---| | Ordinary non-static data member | No | accessed through `const Cache*` | | Member declared `mutable` | Yes | `mutable` nullifies the const of the containing object | | Static data member | Yes | it is not part of the object | | Object reached through a pointer member | Yes | the pointer becomes `T* const`, the pointee stays `T` | | Global or local variables | Yes | they are not reached through `this` | The pointer row is the one interviewers probe. If `Cache` holds `int* counts_`, a const member function cannot reseat `counts_`, but `*counts_ = 0` compiles. The guarantee is **shallow**: it covers the object's own bytes, not what it points to. Owning types such as `std::vector` restore deep constness by offering `const` overloads that return `const` references. ## Overloading on const Because `const` is part of the function's type, a class can provide two versions and let overload resolution choose by the object's constness: 1. `int& at(int i)` is selected for a non-const `Cache`, so callers can write `c.at(0) = 10`. 2. `const int& at(int i) const` is selected for a `const Cache&`, so callers can read but not assign. The const overload must return a `const` reference: inside it `data_[i]` is a `const int` lvalue, and binding `int&` to it would drop the qualifier, which the compiler rejects. ## Casting const away `const_cast<Cache*>(this)` compiles, and modifying through it is defined only when the object was not created `const`. The standard is explicit that any attempt to modify a const object during its lifetime results in undefined behaviour, and a const object whose value is fixed at compile time may even be placed in read-only memory. `mutable` is the supported way to exempt a member; `const_cast` on `this` is a defect waiting for a const object. ## Construction and destruction A constructor can run for a `const` object and assign every member, because const semantics are not applied to an object under construction: they come into effect when the constructor for the most derived object ends. Constructors and destructors cannot themselves be declared `const`. ## Where const belongs in an interface A few habits follow from the mechanism: - Mark every member function that does not change observable state `const`, including simple getters; a missing `const` forces every caller up the chain to drop `const` too. - Accept read-only parameters as `const T&` (or by value for cheap types), which only works if the type's accessors are `const`. - Do not return a non-const reference or pointer to internal state from a `const` function; that hands callers a way around the promise. - Keep `const` and non-const overloads in step; when their bodies are identical, C++23's explicit object parameter can merge them into one function template, a topic for the material on deducing this. ## What callers rely on The promise matters beyond the compiler. Code that holds a `const Cache&` assumes calls cannot change what it observes, and the C++ standard library requires its own functions not to modify objects reached through const arguments, including `this`, which is why concurrent calls to const members of one standard container do not race. A user type with a `const` function that secretly mutates state breaks the same expectation; making such a function correct is the job of `mutable` plus synchronisation.

  • Why must a C++ const member function that returns a member by reference return a const reference?
    Inside the const function the member is a `const` lvalue, because it is reached through `const Cache*`. Binding a plain `int&` or `T&` to it would drop the `const` qualifier, which the compiler rejects. Returning `const T&` keeps the promise: callers holding a const object can read the element but not assign it. The non-const overload returns `T&` for callers that own a modifiable object.
  • A C++ object is defined as const Cache cache; and its constructor assigns members. Why is that allowed?
    The standard says const semantics are not applied to an object under construction; they come into effect when the constructor for the most derived object ends. So the constructor initialises and may assign members freely, and from then until the destructor runs the object is const. Constructors and destructors cannot be declared `const` themselves; they are invoked for const objects anyway.

  • A const member function cannot modify anything, not even mutable members.
  • Marking a member function const also makes the data behind its pointer members const.
  • const on a member function is documentation that the compiler does not enforce.
  • const_cast on this is always safe if only one member is changed.
  • A const object can call any member function that happens not to change state.
open as a page

In C++, what actually differs between a type declared with the keyword struct and one declared with class?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Only two defaults differ: struct members and base classes are public by default, class members and base classes are private. Otherwise the keywords are interchangeable, with the same constructors, virtual functions, templates and access specifiers.

open as a page

In C++, what exactly does a friend declaration grant, and to which code does that access not extend?

level: middleimportance: should knowfreq 48%

basics

~20 s

A friend declaration lets one named function or class use the granting class's private and protected members. The grant is exact: not inherited, not transitive, not reciprocal, and the same whether declared under public or private.

open as a page

In C++, how do static data members and static member functions differ from non-static ones, and where must a static data member be defined?

level: middleimportance: should knowfreq 55%

basics

~20 s

A static data member is one object shared by the class, not part of each instance, and a static member function has no this. Since C++17, inline and constexpr static members are defined in the class; others need one namespace-scope definition.

open as a page

A C++ Cache class has a const get() that updates a hit counter and an internal map; how do you make it correct and thread-safe?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Declare the map and counter mutable so a const get() may update them, then synchronise them: a mutable std::mutex around the map, a std::atomic counter. Callers treat const calls as safe concurrent reads, so unsynchronised mutable state races.

open as a page