skip to content

Classes and Special Members

Access control, constructors and the six special members the compiler may write for you decide how a C++ class behaves when copied, moved or destroyed. Interviewers test the rules.

on this pageshow

explore

questions

15

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++, why initialise members in a constructor's member initializer list rather than assigning them in the constructor body?

level: juniorimportance: must knowfreq 74%

basics

~20 s

Every member is initialised before the constructor body runs, so body assignment means construct, then assign. The initializer list constructs each member once, and is the only way to initialise const members, references and members lacking a default constructor.

open as a page

In C++, what is the rule of three, and what goes wrong when an Image class owning a raw pixel buffer defines only a destructor?

level: juniorimportance: must knowfreq 78%

basics

~20 s

If a class needs a custom destructor, copy constructor or copy assignment, it almost certainly needs all three. An Image with only a destructor gets generated copies that duplicate the pointer, so two Images free one buffer: undefined behaviour.

open as a page

In C++, why does send(30) compile when send takes a const Connection& and Connection has a constructor Connection(int), and what does explicit change?

level: middleimportance: must knowfreq 70%

basics

~20 s

A constructor not marked explicit is a converting constructor, so Connection(int) lets the compiler build a temporary Connection from 30. Marking it explicit keeps it for direct-initialisation and casts but removes the implicit conversion, so send(30) stops compiling.

open as a page

A C++ Connection constructor lists bufferSize_ before buffer_ in its initializer list, yet buffer_ is sized from garbage; why?

level: middleimportance: must knowfreq 68%

basics

~20 s

Members are initialised in the order they are declared in the class, not the order of the initializer list. buffer_ is declared first, so buffer_(bufferSize_) reads bufferSize_ before it is initialised, which is undefined behaviour.

open as a page

In C++, how do you make a class non-copyable or move-only with = delete, and why is deleting its move constructor usually a mistake?

level: middleimportance: must knowfreq 62%

basics

~20 s

Declare the copy constructor and copy assignment = delete, and the moves = default if it should still move. Never delete the moves to mean no move: a deleted function still wins overload resolution, so moving an rvalue fails to compile.

open as a page

A C++ Image class gained a user-declared destructor and now std::move(image) copies its pixels; which special members does the compiler still declare, and why?

level: seniorimportance: must knowfreq 58%

basics

~10 s

A user-declared destructor, even = default, stops the compiler declaring the move constructor and move assignment, while the copy operations are still generated, a deprecated case. std::move(image) then binds to const Image& and copies.

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

Why did adding ConnectionConfig() = default; stop ConnectionConfig{"db", 6432} from compiling when a C++ project moved to C++20?

level: middleimportance: should knowfreq 42%

basics

~20 s

Since C++20 a class with any user-declared constructor, even one written = default, is not an aggregate. ConnectionConfig{"db", 6432} relied on aggregate initialisation, so it now looks for a two-argument constructor that does not exist.

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

In C++, how do delegating constructors and inheriting constructors (using Base::Base) differ in what they initialise and in when the object counts as constructed?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A delegating constructor hands initialisation to another constructor of its class; after the target returns the object exists, so a throw in the delegating body runs the destructor. An inherited constructor builds the base; derived members get only their defaults.

open as a page

In C++, how does copy-and-swap implement Image's assignment operator, what guarantee does it give, and what does it cost compared with member-wise assignment?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Copy-and-swap takes the source by value, swaps *this with that parameter through a non-throwing swap, and lets the parameter's destructor free the old state. Assignment fully succeeds or leaves *this unchanged, but always builds a complete copy.

open as a page

Should a C++ codebase make the rule of zero its default policy, and how would you handle the classes that cannot follow it?

level: principalimportance: should knowfreq 40%

basics

~20 s

Yes, as the default: classes hold resources only through members that already manage them, so the compiler writes correct copies, moves and destructors. The exceptions, resource wrappers, polymorphic bases and out-of-line destructors, declare or delete all five and are reviewed deliberately.

open as a page