Interview Q&A · C++ · 14 questions in this topic
Modern C++ Features — C++ Interview Q&A
What modern C++ actually changed — auto, move, smart pointers, constexpr, lambdas, concepts, ranges and modules. Part of Modern C++ (11 to 23) · 213 questions in the C++ bank.
What did C++11 change and why does every interview ask about it?
Answer
C++11 was the language rebirth: auto, range-for, lambdas, rvalue references/move semantics, smart pointers, nullptr, constexpr, static_assert, threading (thread/mutex/atomic/future), unordered containers, and chrono/regex. It turned C++98 style (manual memory, functors, NULL) into modern style (ownership types, lambdas, deterministic safety).
Every later standard builds on it, so C++11 fluency is the baseline expectation.
Key points
- 1Types — auto, nullptr, strongly-typed enums, static_assert.
- 2Ownership — unique_ptr/shared_ptr, move semantics.
- 3Genericity — lambdas, range-for, variadics, constexpr.
- 4Concurrency — threads, mutexes, atomics, futures in the standard.
Example
auto v = std::vector<int>{1, 2, 3}; for (const auto& x : v) { /* range-for (C++11) */ }
💡 Name one feature from each bucket (types, ownership, genericity, concurrency) to show breadth.
What did C++14 and C++17 each add?
Answer
C++14 completed C++11: generic lambdas (auto params), return-type deduction, digit separators, make_unique, shared timed mutexes. C++17 was the big productivity release: structured bindings, if-init statements, constexpr if, fold expressions, string_view, optional/variant/any, parallel algorithms, filesystem, hardware interference sizes, and inline variables.
Interview shorthand: 14 finished 11, 17 made daily code cleaner and safer.
Example
std::map<int, std::string> m{{1, "a"}}; if (auto it = m.find(1); it != m.end()) { /* if-init (C++17) */ } auto [k, v] = *it; // structured binding (C++17)
What did C++20 and C++23 add?
Answer
C++20: concepts, ranges/views, coroutines, modules, constexpr expansion (vector/string), three-way comparison (<=>), designated initializers, bit_cast, jthread/stop_token, calendars/timezones, and formatting groundwork. C++23: std::expected, std::print, ranges extensions (zip/views), flat containers, multidimensional span, stacktrace, and constexpr hardening.
Practical interview take: concepts plus ranges change how generic code is written; modules change how it is built.
Example
#include <compare> struct Point { int x, y; auto operator<=>(const Point&) const = default; };
💡 Concepts, ranges, coroutines, modules — those four carry the C++20 answer.
What is `decltype` and how does `decltype(auto)` differ from `auto`?
Answer
decltype queries an expression type without evaluating it: decltype(x) for declared types, with reference-ness following value category for parenthesized expressions. auto drops references/top-const; decltype(auto) preserves the exact type including references — essential for perfect-returning wrappers.
Rule: auto for values, auto&/const auto& for aliases, decltype(auto) for transparent forwarding returns.
Example
int x = 0; int& r = x; auto a = r; // int (reference dropped) decltype(auto) b = r; // int& (reference kept)
What are `std::optional`, `std::variant` and `std::any` for?
Answer
optional<T> is a nullable value without sentinel hacks or out-params — empty or holding T. variant<Ts...> is a type-safe union holding exactly one alternative with visit-based dispatch. any holds anything with runtime type checks (niche: plugins, scripting bridges).
Prefer optional over sentinel returns, variant over void*/unions for closed type sets, and reserve any for genuinely open type sets.
Example
#include <optional> #include <variant> std::optional<int> find_id(std::string_view name); // empty = not found std::variant<int, std::string> v = 42; // std::visit(overloaded{...}, v); // type-safe dispatch
💡 Nullable, closed-union, open-anything is the three-way split.
What is structured binding and what are its limitations?
Answer
Structured bindings (auto [a, b] = ...) unpack structs, arrays, pairs and tuples by name. They introduce aliases, not independent variables (binding a member means writing through it mutates the source), and cannot mix with existing declarations or default captures per-name in lambdas (capture the whole binding instead).
Use by-value for snapshots, by-ref for mutation, and keep bindings const unless mutation is intended.
Example
struct P { int x, y; }; P p{1, 2}; auto& [x, y] = p; // aliases: x refers to p.x y = 9; // mutates p.y
What is `if constexpr` and why is it better than tag dispatch?
Answer
if constexpr evaluates the condition at compile time and discards the dead branch — including ill-formed code for the other branch. It replaces SFINAE overload sets and tag-dispatch helpers for compile-time branching with plain readable control flow.
Use it for type-dependent logic inside one template instead of two overloads; the discarded branch still must parse, just not instantiate.
Example
template<class T> std::string kind() { if constexpr (std::is_integral_v<T>) return "int-like"; else return "other"; }
💡 Compile-time branch with dead-code discard is the definition; replacing dispatch boilerplate is the payoff.
What is the spaceship operator (`<=>`) and what comparison categories exist?
Answer
The spaceship operator performs three-way comparison in one declaration: strong_ordering (exact rank, e.g. ints), weak_ordering (equivalence classes, e.g. case-insensitive strings), partial_ordering (unordered values, e.g. NaN floats). = default generates all relational operators consistently.
Default it for value types to get correct, consistent comparisons without hand-writing six operators.
Example
#include <compare> struct Version { int major, minor; auto operator<=>(const Version&) const = default; // all six ops };
What are coroutines (C++20) at a high level?
Answer
Coroutines are functions that can suspend and resume (co_await, co_yield, co_return), with the compiler generating a state machine plus a promise object controlling behavior. The standard ships the machinery; libraries provide task/generator types on top (awaitables, async frameworks, lazy generators).
Use them for async I/O pipelines and lazy sequences; reach for them only with a coroutine-capable library, since raw promise types are expert-level plumbing.
Example
// sketch: generator via a library type (standard has no std::generator until C++23) // Generator<int> seq() { co_yield 1; co_yield 2; }
💡 Suspend-resume plus promise-customization is the corridor-level summary; library types are the practical caveat.
What are C++20 modules and what problem do they solve?
Answer
Modules (import x;) replace textual header inclusion with compiled module interfaces: faster builds (no re-parsing headers per TU), no macro leakage, no include-order fragility, and explicit export control. Adoption is gradual — build-system support, macro-heavy codebases and header-only library ecosystems migrate slowly.
Interview framing: headers are copy-paste; modules are compiled boundaries.
Example
// math.cppm export module math; export int add(int a, int b) { return a + b; } // user.cpp // import math;
What is `constexpr` expansion in C++20 (vector/string) and why does it matter?
Answer
C++20 allows constexpr allocation with compile-time freeing, so std::vector and std::string work in constant evaluation (results must be compile-time values, all allocation freed by evaluation end). Combined with consteval and is_constant_evaluated, more initialization moves to compile time with zero runtime cost.
It matters for verified lookup tables, parsers and embedded constants computed once by the compiler.
Example
constexpr int table_size() { std::vector<int> v{1, 2, 3}; // ok in constexpr (C++20) return (int)v.size(); } static_assert(table_size() == 3);
What are scoped enums (`enum class`) and why are they better?
Answer
Scoped enums do not leak enumerators into the enclosing scope, do not implicitly convert to int, and default to int underlying type with explicit sizing available. Unscoped enums convert silently and collide across enums in one scope.
Always prefer enum class; specify the underlying type (: uint8_t) for serialization and ABI stability.
Example
enum class Color : unsigned char { Red, Green, Blue }; // int x = Color::Red; // error: no implicit conversion int y = static_cast<int>(Color::Red); // explicit only
💡 No leakage plus no silent int conversion is the complete justification.
What is `std::string_view` lifetime discipline in one paragraph?
Answer
string_view is a non-owning observation: copying is cheap, but the viewed characters must outlive every view. Never return views to locals, never store views past owner mutation/reallocation, and never bind a view to a temporary that dies at the semicolon.
Function parameters are the sweet spot (accept string, literal and view with zero copies); storage and returns are the danger zone.
Example
std::string_view first_word(std::string_view s); // safe: views in, view out of input // std::string_view bad() { std::string s = "x"; return s; } // dangling!
What C++ habits mark code as genuinely modern (C++17/20 style)?
Answer
Ownership in types (unique_ptr, no raw new/delete), const-correct references and views for inputs, algorithms over raw loops, auto where it adds clarity, scoped enums, structured bindings, optional/variant over sentinels and unions, string_view parameters, and concepts/constraints on templates.
Modern is not version-number bingo — it is expressing ownership, lifetime and intent in the type system.
Key points
- 1Ownership — smart pointers, RAII, no manual delete.
- 2Views — string_view/span parameters, no copies.
- 3Algorithms + ranges — named operations over raw loops.
💡 Close with the principle (intent in the type system), not a feature list — that reads senior.
Recommended resourcesAffiliate links · may earn us a commission