Skip to content
Tutorials Center
My learning

Topics

Lesson 171 of 171 ยท Practice and Review

C++ Interview Questions

50 common C++ interview questions with clear answers, from pointers, references and const to virtual functions, smart pointers, move semantics, the STL and threads.

C++ interviews check two things: whether you know how the language behaves (object lifetimes, copies, undefined behavior, what the compiler generates for you) and whether you can explain it in plain words. This page collects 50 questions that come up again and again, grouped by level and topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson and review it. A few questions ask you to read code and predict its output; make your prediction first, then press Run.

Tip: a short correct answer with a tiny example beats a long recital. Mention trade-offs ("std::list never invalidates iterators, but it's slow to walk because its nodes are scattered in memory") and modern alternatives ("today I'd use std::unique_ptr here"). That's what separates a senior answer from a junior one.

Junior level

Language basics

What is C++, and how does it differ from C?

C++ is a compiled, statically typed, multi-paradigm language that started as "C with classes" and grew into its own language. It keeps C's low-level control (pointers, manual memory layout, no garbage collector) and adds classes with constructors and destructors, references, templates, exceptions, namespaces, function overloading, lambdas and a large standard library (containers, algorithms, strings, smart pointers, threads). Most C code compiles as C++, but not all: for example, C++ requires a cast from void* and reserves keywords such as new and class. See C and C++.

What happens when you build a C++ program?

Four stages. The preprocessor handles #include, #define and #if, producing one translation unit per .cpp file. The compiler turns each translation unit into an object file of machine code. The linker combines the object files and libraries, resolving each function or variable name to its single definition, and produces the executable. Then the program runs. Errors in the first stages are compile errors; "undefined reference" errors come from the linker. See How C++ Works.

What is the difference between a declaration and a definition?

A declaration introduces a name and its type (int add(int, int);, extern int count;, class Widget;). A definition also provides the thing itself: the function body, the storage for a variable, the full class. You can declare something many times, but the one-definition rule says a non-inline function or variable must be defined exactly once in the whole program. Headers therefore contain declarations (plus inline functions, templates and class definitions), and .cpp files contain the definitions. See Header Files.

What is the difference between a pointer and a reference?

A reference is an alias for an existing object: it must be initialized, can't be null in a correct program, and can't be reseated to refer to something else. A pointer is an object holding an address: it can be null, can change what it points to, supports arithmetic, and needs * or -> to reach the target. Use references for parameters and return values that always refer to something; use pointers (or std::optional, or smart pointers for ownership) when "nothing" is a valid state or the target can change. See References and Pointers.

When do you pass by value, by reference and by const reference?

Pass small, cheap-to-copy types (int, double, iterators, std::string_view, std::span) by value. Pass large read-only objects (std::string, std::vector, your classes) by const& to avoid a copy. Pass by non-const reference only when the function must modify the caller's object. If the function stores its own copy anyway, taking the parameter by value and moving from it is a good pattern: Person(std::string name) : name_(std::move(name)) {}. See Parameters.

What does const mean, and how is constexpr different?

const means "this can't be modified through this name"; the value may still be computed at run time (const int n = read_number();). constexpr on a variable means the value is a compile-time constant, so it can be used as an array size or template argument. A constexpr function can run at compile time when its arguments are constants, but may also run at run time; a consteval function must run at compile time. On member functions, const means the function doesn't change the object. See Constants and const Member Functions.

What does auto deduce?

auto uses template argument deduction rules: it takes the type of the initializer but drops top-level const and references. So with const std::string& name = person.name;, auto copy = name; is a plain std::string copy. Write const auto& to bind without copying, auto& to modify in place, and auto&& for a forwarding reference. decltype(expr) gives the declared type, including references. See Type Deduction with auto.

What is the difference between a struct and a class?

Only the defaults: members and base classes are public by default in a struct and private by default in a class. Everything else (constructors, member functions, inheritance, templates) works identically. By convention, struct is used for simple aggregates whose data members are the interface, and class for types with invariants and private data. See Classes and Objects.

Is there a difference between ++i and i++?

++i increments and returns the variable itself; i++ returns a copy of the old value and then increments. For int the compiler generates the same code when the result is unused. For class types like iterators, i++ must create and return a copy, so ++i is never slower and is the habit to build. See Assignment and Increment Operators.

Why is using namespace std; discouraged?

It pulls every name from std into the current scope, and std contains hundreds of common names (count, distance, size, data, byte). Your own functions can then clash with them, or calls can silently pick a different overload when a new standard adds a name. In a header it's worse, because it leaks into every file that includes the header. Prefer std:: prefixes, or targeted using std::string; declarations in a .cpp file or function. See Namespaces.

What is undefined behavior? Give examples.

Undefined behavior (UB) is code for which the standard places no requirements on what happens. The program may crash, print garbage, seem to work, or behave differently with another compiler or optimization level, because the optimizer is allowed to assume UB never happens. Common causes: reading uninitialized variables, out-of-bounds access, dereferencing null or dangling pointers, signed integer overflow, data races, and delete-ing something twice. Sanitizers (-fsanitize=address,undefined) find many of these at run time. See Undefined Behavior.

Code reading: values and references

Predict both numbers before you run it.

C++ Predict the output: copies and references

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.

Explain the output.

It prints n = 11, copy = 110. twice doubles its own copy, so n stays 5; twice_ref doubles n itself, making it 10. copy is an independent int with the value 10, which becomes 110. alias is another name for n, so alias += 1 makes n 11.

Mid level

Classes and object-oriented programming

What is RAII?

Resource Acquisition Is Initialization: a resource (memory, a file, a lock, a socket) is acquired in an object's constructor and released in its destructor. Because C++ destroys local objects automatically when they go out of scope, including during stack unwinding after an exception, the resource is always released, with no finally blocks and no manual cleanup calls. std::vector, std::string, std::unique_ptr, std::fstream and std::lock_guard are all RAII types. See Destructors and RAII.

Why use a member initializer list, and in what order are members initialized?

The initializer list initializes members directly; assignments in the constructor body happen after every member has already been default-constructed. It's required for const members, reference members, and members or bases without a default constructor, and it avoids double work for types like std::string. Members are always initialized in the order they are declared in the class, not the order you write them in the list, so a member initialized from another member declared later reads garbage. GCC warns about this with -Wreorder (part of -Wall). See Constructors.

How do virtual functions work?

Calling a virtual function through a base-class pointer or reference runs the override of the object's dynamic (actual) type. Compilers typically implement this with a vtable: each polymorphic class has a table of function pointers, and each object stores a hidden pointer to its class's table, so a virtual call is an indirect call through that table. The costs are a pointer per object, an indirect call, and usually no inlining. Mark overrides with override so the compiler checks that they really override something. See Virtual Functions and Polymorphism.

Why does a polymorphic base class need a virtual destructor?

If you delete a derived object through a base-class pointer and the base destructor isn't virtual, the behavior is undefined; in practice, only the base part is destroyed, so the derived members (and their resources) leak. A virtual destructor makes destruction dispatch to the derived destructor first. The rule: a class meant to be used polymorphically gets virtual ~Base() = default;. If deletion through the base should be impossible, make the destructor protected and non-virtual instead.

What is object slicing?

Copying a derived object into a variable of the base type copies only the base part; the derived data and the derived behavior are "sliced off". It happens with pass-by-value parameters (void draw(Shape s)), assignments to base objects, and containers like std::vector<Shape>. Use references, pointers or std::vector<std::unique_ptr<Shape>> for polymorphic objects. Making polymorphic bases non-copyable, or abstract, prevents accidental slicing.

What happens if you call a virtual function from a constructor?

It calls the version for the class whose constructor is currently running, not the most derived override. While the Base constructor runs, the Derived part doesn't exist yet, so the object's dynamic type is Base; the same applies in destructors, in reverse. Calling a pure virtual function this way is undefined behavior. If derived classes need to customize construction, pass the information as constructor arguments or use a factory function.

Code reading: construction, virtual calls and slicing

C++ Predict the output: virtual calls and slicing

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.

Explain the output.

Construction runs base first: inside Base() the object is still a Base, so name() returns "Base"; inside Derived() it returns "Derived". by_value receives a sliced copy that really is a Base, so it prints Base, and that copy is destroyed when the function returns (the first ~Base). by_ref sees the real object and prints Derived. At the end of main, d is destroyed in reverse order of construction: ~Derived, then ~Base.

What are the rule of zero, the rule of three and the rule of five?

The five special members that manage copying, moving and cleanup are the destructor, copy constructor, copy assignment, move constructor and move assignment. Rule of three: if a class needs a custom destructor, copy constructor or copy assignment, it almost certainly needs all three, because it manages a resource. Rule of five: add the two move operations so the resource can be transferred cheaply. Rule of zero: the best option is to write none of them, by holding resources in members that already manage themselves (std::vector, std::string, std::unique_ptr). See The Rule of Zero, Three and Five.

When is the copy constructor called, and when is copy assignment called?

The copy constructor creates a new object from an existing one: Widget b = a;, Widget b(a);, passing by value, and returning by value when no elision applies. Copy assignment replaces the contents of an object that already exists: b = a;. The difference matters because assignment must release the old contents first, and must handle self-assignment (a = a); the copy-and-swap idiom covers both. See Copy Constructors and Copy Assignment.

What does the explicit keyword do?

It stops a constructor (or conversion operator) from being used for implicit conversions. Without it, a constructor Buffer(std::size_t size) lets Buffer b = 42; compile, and a function taking const Buffer& silently accepts 42. Mark single-argument constructors explicit unless the implicit conversion is natural, as for a Fraction built from an integer. See Constructors.

What is the difference between overloading, overriding and hiding?

Overloading is several functions with the same name and different parameters in the same scope, chosen at compile time. Overriding is a derived class replacing a base class's virtual function with the same signature, chosen at run time. Hiding happens when a derived class declares any function with the same name as a base function: it hides all base overloads of that name, even with different parameters, unless you add using Base::name;. override catches mismatched signatures; final stops further overriding or derivation. See Inheritance.

What is the diamond problem, and how does virtual inheritance solve it?

If B and C both derive from A, and D derives from both B and C, then D contains two A subobjects, so d.a_member is ambiguous and the data is duplicated. Declaring the inheritance as class B : virtual public A (and the same for C) makes D share a single A, and the most derived class (D) is then responsible for constructing it. Virtual inheritance adds indirection, so it's mostly used for interface-like bases. See Multiple and Virtual Inheritance.

Memory and smart pointers

What is the difference between the stack and the heap?

Local variables live in automatic storage (the stack): allocation is nearly free, the size is fixed at compile time, and objects are destroyed automatically at the end of their scope. Dynamic storage (the heap) is requested at run time, is much larger, and lives until it's explicitly released, which is slower and needs an owner. In modern C++ you rarely touch the heap directly: std::vector, std::string and smart pointers allocate on the heap but are themselves ordinary local objects that clean up after themselves. See Memory Layout.

How do new and delete differ from malloc and free?

new allocates memory and runs the constructor, returns a correctly typed pointer, and throws std::bad_alloc on failure; delete runs the destructor and frees the memory. malloc and free only handle raw bytes, return void* and signal failure with nullptr. Never mix them (free on new-ed memory is UB), and match new[] with delete[]. In application code, prefer containers and std::make_unique over both. See Dynamic Memory.

Compare unique_ptr, shared_ptr and weak_ptr.

std::unique_ptr is exclusive ownership: move-only, as small and fast as a raw pointer, and the default choice. std::shared_ptr is shared ownership through a reference-counted control block: copying it increments an atomic count, and the object dies when the last owner goes away. std::weak_ptr observes an object owned by shared_ptrs without keeping it alive; call lock() to get a shared_ptr if the object still exists. Raw pointers and references remain fine for non-owning access. See std::unique_ptr and shared_ptr and weak_ptr.

Why prefer make_unique and make_shared over new?

They keep new out of your code, so every allocation is owned from the first moment and there's no window for a leak. std::make_shared also allocates the object and its control block in one allocation instead of two, which is faster and more cache-friendly. One trade-off: with make_shared, the memory of a large object can't be freed until the last weak_ptr is gone too, because it shares a block with the control block.

How can shared_ptr leak memory?

Through reference cycles. If two objects hold shared_ptrs to each other (a parent and child, or a doubly linked list), each keeps the other's count above zero, so neither destructor ever runs after the outside owners are gone. Break the cycle by making one direction a std::weak_ptr, usually the "back" pointer (child to parent). See the next code-reading question.

Code reading: a shared_ptr cycle

C++ Predict the output: shared_ptr cycles

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.

Explain the output.

In the first scope, a1 is owned by a and by b1->prev_strong, so its count is 2. When the scope ends, both counts only drop to 1, so no destructor runs: a1 and b1 leak. In the second scope the back pointer is a weak_ptr, so a2's count is 1. When a goes away, a2 is destroyed, which releases next, which destroys b2. That's why ~Node a2 prints before ~Node b2.

What is a dangling pointer or reference?

A pointer, reference, iterator or view that still refers to an object whose lifetime has ended. Classic sources: returning a reference or pointer to a local variable, keeping an iterator after the vector reallocated, a std::string_view of a temporary string, a lambda that captures a local by reference and runs later, and using memory after delete. Using it is undefined behavior. The cure is clear ownership: return by value, keep views shorter-lived than their owners, and capture by value in long-lived callbacks. See Undefined Behavior.

What does std::move actually do?

Nothing at run time. std::move(x) is just a cast to an rvalue reference (static_cast<T&&>(x)), which tells overload resolution "you may steal from this". The actual moving happens in a move constructor or move assignment that is then selected. After a move, the source is in a "valid but unspecified" state: you may destroy it or assign a new value, but you shouldn't rely on its contents. std::move on a const object silently copies, because a const T&& can't bind to the move constructor's T&&. See Move Semantics.

Why should move constructors be noexcept?

When a std::vector grows, it must transfer its elements to the new buffer while keeping the strong exception guarantee: if something throws, the original vector must be unchanged. A move that might throw could leave both buffers half-moved, so the vector copies elements instead, unless the move constructor is noexcept (or the type can't be copied). Marking moves noexcept therefore turns expensive copies into cheap moves. The compiler-generated move operations are noexcept when all members' moves are. The code below shows the difference.

Code reading: noexcept and vector growth

C++ Predict the output: noexcept moves

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.

Explain the output.

Both runs build 100 elements in place with emplace_back, so every copy or move comes from reallocation. With GCC's doubling growth (capacities 1, 2, 4, โ€ฆ, 128), reallocations transfer 1 + 2 + 4 + โ€ฆ + 64 = 127 elements. With a noexcept move constructor, those are 127 moves and 0 copies; without noexcept, the vector falls back to 127 copies and 0 moves. (Growth factors are implementation-defined, so other libraries may print different counts, but the copy-versus-move difference is the same.)

The standard library

When would you choose vector, deque or list?

Default to std::vector: contiguous memory, O(1) indexing, amortized O(1) push_back, and by far the best cache behavior. Choose std::deque when you need fast insertion at both ends with indexing. Choose std::list only when you need iterators and references that never invalidate, or O(1) splicing of elements between lists; its scattered nodes make traversal slow, so even middle insertions are often faster in a vector for small and medium sizes. See std::deque, std::list and std::forward_list.

What is the difference between std::map and std::unordered_map?

std::map is a balanced binary search tree (usually red-black): keys stay sorted, operations are O(log n), and you get ordered iteration and range queries with lower_bound. std::unordered_map is a hash table: operations are O(1) on average (O(n) worst case with bad hashing), iteration order is unspecified, and the key type needs a hash function and ==. Choose unordered_map for pure lookups, and map when you need order or predictable worst-case time. See std::map and std::unordered_map.

What is iterator invalidation? Give examples for vector.

An iterator (or pointer or reference) is invalidated when the container operation it depends on moves or destroys the element; using it afterward is undefined behavior. For std::vector: any operation that reallocates (push_back beyond capacity, reserve, insert) invalidates everything; insert and erase invalidate the elements at and after the position; clear invalidates all. The classic bug is erasing inside a range-for loop. Use it = v.erase(it) in an iterator loop, or better, std::erase_if. See Iterators.

What is the difference between reserve and resize?

reserve(n) changes the capacity only: it allocates room for at least n elements but adds none, so size() is unchanged and indexing past it is still out of bounds. resize(n) changes the size: it creates value-initialized elements (or destroys extra ones), so v[i] is valid for every i < n. Use reserve before a loop of push_back calls when you know the final count. See std::vector in Depth.

What is the difference between push_back and emplace_back?

push_back takes an already-constructed object and copies or moves it into the vector. emplace_back takes constructor arguments and builds the element directly in the vector's storage, so points.emplace_back(1, 2) constructs a Point in place. For an existing object both do the same; emplace_back helps when building from arguments. Be careful: because it calls constructors directly, emplace_back can invoke explicit constructors you didn't intend, such as vector<vector<int>>::emplace_back(1000000).

How do you remove elements from a vector that match a condition?

In C++20 and later, call std::erase_if(v, predicate) (or std::erase(v, value)). Before C++20, the erase-remove idiom: v.erase(std::remove_if(v.begin(), v.end(), predicate), v.end());. remove_if doesn't shrink the vector; it shifts the elements to keep toward the front and returns the new logical end, which erase then cuts off. Both run in O(n), unlike erasing elements one by one inside a loop, which is O(nยฒ). See Algorithms: Transforming and Modifying.

Senior level

Templates and modern C++

Why are templates usually defined in header files?

A template isn't code until it's instantiated with concrete types, and the compiler can only instantiate it in a translation unit where it sees the full definition. If Stack<T>::push were defined only in stack.cpp, a file using Stack<int> would compile against the declaration, but no Stack<int>::push would ever be generated, giving a linker error. The alternatives are explicit instantiation in the .cpp file for a known set of types, or C++20 modules. See Function Templates and Class Templates.

What are concepts, and why are they better than SFINAE?

A concept is a named compile-time predicate on types, such as std::integral<T> or a custom requires expression, used to constrain templates: template <std::integral T> T gcd(T a, T b);. Before C++20, the same was done with SFINAE tricks like std::enable_if_t<...>, which are hard to read and give long, cryptic errors. Concepts state the requirements in the interface, overload cleanly on constraints, and make the compiler report "constraint not satisfied" at the call site. See Concepts and Constraints and Type Traits.

What is perfect forwarding?

Passing arguments through a function template to another function while preserving whether each was an lvalue or an rvalue, so copies stay copies and moves stay moves. It uses a forwarding reference (T&& where T is deduced, or auto&&) together with std::forward<T>(arg): template <typename... Args> void emplace(Args&&... args) { construct(std::forward<Args>(args)...); }. Without std::forward, a named parameter is always an lvalue and would be copied. See Variadic Templates.

What is copy elision, and what does C++17 guarantee?

Copy elision lets the compiler construct a returned object directly in the caller's storage, skipping the copy or move. Since C++17 it's guaranteed when you return a prvalue (return Widget(args);) or initialize from one, and it works even for types that can't be copied or moved. Named return value optimization (Widget w; ...; return w;) is still optional but nearly universal, and if it doesn't happen the returned local is moved, not copied. That's why returning large objects by value is the right default, and why return std::move(local); is a pessimization. See Returning Values.

How do you choose between exceptions, std::optional and std::expected?

Use exceptions for failures that are rare, can't be handled locally, and must not be ignored, especially in constructors, which can't return an error. Use std::optional<T> when "no value" is a normal outcome that needs no explanation, such as a lookup that misses. Use std::expected<T, E> (C++23) when the caller should handle the failure and needs to know why, such as parsing. Some domains (games, embedded, real-time) disable exceptions entirely and rely on the last two. See Error Handling Without Exceptions and optional, variant, any and expected.

What are the exception safety guarantees?

The nothrow guarantee: the operation never throws (destructors, swaps, moves marked noexcept). The strong guarantee: if it throws, the program state is as if it was never called (commit-or-rollback, such as vector::push_back for most types). The basic guarantee: if it throws, no resources leak and all objects remain valid, but their values may have changed. RAII gives you the basic guarantee almost for free; the copy-and-swap idiom is a common way to get the strong one. Destructors must not throw: they're implicitly noexcept, so an escaping exception calls std::terminate. See Exception Safety and noexcept.

What does a lambda compile into, and what are the capture pitfalls?

Each lambda expression creates an unnamed closure class with an operator(); captured variables become its data members (copies for [x], references for [&x]). Its call operator is const unless the lambda is mutable. The main pitfall is lifetime: [&] captures references, so a lambda stored as a callback or run on another thread after the function returns refers to dead locals. A subtler one is [=] in a member function before C++20, which captured this (a pointer), not a copy of the object. See Lambda Expressions.

Concurrency

What is a data race, and how is it different from a race condition?

A data race is two threads accessing the same memory location at the same time, at least one of them writing, without synchronization (a mutex or atomics). In C++ it's undefined behavior, not just a wrong result. A race condition is a broader logic bug where the outcome depends on timing, even if every individual access is synchronized, for example "check that the file doesn't exist, then create it". Mutexes and atomics remove data races; avoiding race conditions requires designing operations to be atomic as a whole. See Mutexes and Locks.

Compare lock_guard, unique_lock and scoped_lock.

All three are RAII wrappers that unlock automatically. std::lock_guard locks one mutex for its whole scope and nothing else. std::scoped_lock (C++17) can lock several mutexes at once using a deadlock-avoidance algorithm, and is the modern default. std::unique_lock is movable and flexible: it can lock later, unlock early, try-lock with a timeout, and it's required by std::condition_variable::wait. For readers and writers, std::shared_mutex with std::shared_lock allows many concurrent readers. See Mutexes and Locks and Condition Variables.

What causes deadlock, and how do you avoid it?

A deadlock happens when threads wait for each other forever, typically when thread 1 holds mutex A and waits for B while thread 2 holds B and waits for A. Avoid it by locking multiple mutexes together with std::scoped_lock(a, b), always acquiring locks in one global order, keeping critical sections short, and never calling unknown code (callbacks, virtual functions) while holding a lock. Also, a condition variable must always be waited on with a predicate, or a missed notification can block forever.

When do you use std::atomic instead of a mutex?

Use std::atomic for single variables with simple operations: counters, flags, a pointer swap, or lock-free algorithms built on compare_exchange. Use a mutex when several variables must change together, or an invariant spans more than one value; two atomics updated separately don't make a consistent pair. Atomics default to memory_order_seq_cst, the easiest to reason about; acquire/release and relaxed can be faster but are easy to get wrong. Note that volatile is not a threading tool in C++. See Atomics and the Memory Model.

Compare std::thread, std::jthread and std::async.

std::thread starts a thread, but you must call join() or detach() before it's destroyed, or the program calls std::terminate. std::jthread (C++20) joins automatically in its destructor and supports cooperative cancellation through a std::stop_token, so it's the better default. std::async runs a task and returns a std::future for the result; future.get() waits and rethrows any exception from the task. Pass std::launch::async to guarantee a new thread, and remember that the future returned by std::async blocks in its destructor until the task finishes. See Threads and std::async, Futures and Promises.

Performance and design

Why is a vector usually faster than a list, even for insertions?

Modern CPUs are fast at computation and slow at fetching memory. A vector's elements are contiguous, so traversals use whole cache lines and the hardware prefetcher predicts the next access. List nodes are scattered heap allocations, so every step can be a cache miss, plus each node costs an allocation and two extra pointers. Finding the insertion position in a list is O(n) anyway, which is why a vector with an O(n) shift often wins in practice. Measure before choosing otherwise. See Writing Fast C++.

What are static and dynamic polymorphism, and when would you choose each?

Dynamic polymorphism uses virtual functions: one compiled function works with any derived type through a base pointer, chosen at run time, at the cost of an indirect call and usually heap-allocated objects. Static polymorphism uses templates, concepts or CRTP: the type is known at compile time, calls can be inlined, but each type produces its own instantiation and the set of types must be known where the code compiles. Choose dynamic polymorphism for open, heterogeneous collections (plugins, a scene of shapes), and static polymorphism for hot code paths and generic algorithms. See Design Patterns in C++.

Language edge cases

These questions come up when an interviewer wants to see whether you know what the language promises and where it stops promising anything.

What does volatile do, and is it a threading tool?

volatile tells the compiler that every read and write of the object is an observable side effect, so it may not cache the value in a register, merge accesses or remove them. It exists for memory the compiler cannot see changing: memory-mapped hardware registers and variables changed by a signal handler or setjmp/longjmp. It provides no atomicity and no ordering between threads: two threads touching a volatile int is still a data race and therefore undefined behavior. Use std::atomic for shared variables and a mutex for shared state (see Atomics and the Memory Model). A volatile object can also be const, which means "this code may not write it, but something else may".

What is the difference between delete and delete[]?

new allocates one object and new[] allocates an array and usually stores the element count somewhere, so the runtime knows how many destructors to call. delete destroys one object; delete[] destroys every element in reverse order and then frees the block. Using the wrong form is undefined behavior: delete p on an array runs one destructor and passes the wrong address to the allocator, and delete[] p on a single object reads a count that was never stored. The compiler usually cannot tell, because both pointers have the same type, which is why std::vector and std::unique_ptr<T[]> are the better choices. Deleting a null pointer is always safe. See Dynamic Memory.

Can code run before main? Can a program have no main?

Yes to the first. Objects with static storage duration at namespace scope are constructed before main starts, so their constructors, and any function used in their initializers, run first. That is also the source of the "static initialization order fiasco": the order between different translation units is unspecified, so one global must not use another global from a different file during initialization. A function-local static is initialized on first use and avoids the problem.

A hosted C++ program must have a function named main; a program without one is ill-formed (the linker usually reports an undefined main). Freestanding environments such as kernels and some embedded systems define their own entry point instead. You may not call main yourself in C++, take its address, or declare it as static or inline.

What happens with duplicate keys in std::map, std::set and their multi versions?

std::map and std::set hold unique keys. insert and emplace on an existing key do nothing and report false (the old value stays); operator[] on a map returns a reference to the existing value, or default-constructs a new one if the key is missing; insert_or_assign overwrites. std::multimap and std::multiset allow duplicates and keep equal keys in insertion order. Equality is decided by the comparator, not by ==: two keys are the same when neither is less than the other. See map and multiset and multimap.

What happens when an exception is thrown inside a function template?

Nothing special: a template is instantiated into an ordinary function, and exceptions propagate through it like through any other function. Two points matter. First, a template cannot know what the type it is given will throw, because operations such as T(other) or a + b may throw for some types and not others, so generic code should state its guarantee conditionally with noexcept(noexcept(expression)) or noexcept(std::is_nothrow_move_constructible_v<T>). Second, exception safety has to hold for every T: if the third element's copy throws, the elements already built must be destroyed (RAII, or a catch-and-rethrow). Standard containers use std::move_if_noexcept for exactly this reason. See Exception Safety and noexcept.

The program below demonstrates two of these answers: code that runs before main, and what each container does with a duplicate key.

C++ Before main, and duplicate keys

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Inside Base's constructor, a virtual function name() is called on an object being built as Derived. Which version runs?

    During base construction the object's dynamic type is Base. Derived's members haven't been initialized, so calling its override would be unsafe.
  2. 2. What does std::move(x) do by itself?

    std::move is only a cast. The actual transfer happens in the move operation that overload resolution then selects, if there is one.
  3. 3. Two objects hold std::shared_ptrs to each other, and all other owners go away. What happens?

    Reference counting can't detect cycles. Make one of the pointers a std::weak_ptr to break the cycle.
  4. 4. Why does std::vector copy elements during reallocation when the move constructor isn't noexcept?

    vector uses std::move_if_noexcept. If the move might throw and the type can be copied, copying keeps the original elements intact if an exception occurs.

Summary

  • Junior questions check the foundations: the build process, declarations and the ODR, pointers vs references, parameter passing, const/constexpr, auto, and what undefined behavior means.
  • Mid-level questions focus on object lifetimes and ownership: RAII, initialization order, virtual dispatch and virtual destructors, slicing, the rule of zero/three/five, smart pointers, move semantics and noexcept.
  • STL questions test container choice, complexity, iterator invalidation and the subtle differences between similar member functions.
  • Senior questions cover templates and concepts, perfect forwarding, copy elision, error-handling strategy, exception safety, concurrency primitives and performance trade-offs.
  • In every answer, a clear explanation with a tiny example and its trade-offs is what interviewers reward.

You've reached the end of the C++ course. Keep practicing with the exercises and the 40 classic programs, keep the cheat sheet close, and come back to the C++ course overview whenever you want to review a topic. Happy coding!