Skip to content

C++ Interview Questions & Answers

All 200 unique questions in one place — 60 easy, 96 medium, 44 hard — grouped by topic.

Practise by topic

Solved overallStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is C++ and how is it different from C?

Save to ▾
Show answer
C++ is a compiled, statically typed, multi-paradigm language built on top of C. It adds classes, inheritance, templates, exceptions, namespaces, references, function overloading and a large Standard Library, while C is purely procedural. C++ keeps the low-level control and speed of C, which is why it is used in game engines, trading systems, browsers, databases, compilers and embedded firmware where performance and hardware access matter.
02

What is the difference between a declaration and a definition?

Save to ▾
Show answer
A declaration tells the compiler that a name of a certain type exists, for example extern int count; or void f(int);. A definition actually allocates storage or provides the function body. You may declare a name many times but define it only once across the whole program, which is the One Definition Rule. Headers normally hold declarations and .cpp files hold definitions.
03

What are the fundamental data types in C++ and their typical sizes?

Save to ▾
Show answer
The main types are bool, char, short, int, long, long long, float, double and long double. On a typical 64-bit Linux system char is 1 byte, short 2, int 4, long 8, long long 8, float 4 and double 8. The standard only guarantees minimum ranges, so check with sizeof, and use fixed-width types such as int32_t or uint64_t from <cstdint> when the exact size matters.
04

What is the difference between ++i and i++?

Save to ▾
Show answer
++i increments the variable and returns the updated object, while i++ returns a copy of the old value and then increments. For an int the optimiser makes them equally fast. For iterators and class types i++ must create a temporary copy, so ++i is preferred in loops. Example: int a = 5; int b = a++; leaves b equal to 5 and a equal to 6.
05

A teammate added using namespace std; to a shared header file. What problems can this cause?

Save to ▾
Show answer
Every file that includes the header now has all std names pulled into the global namespace. This can cause ambiguous calls or silently pick the wrong function when user code defines names like count, distance, min or data. The problem spreads to every dependent file and is hard to trace. I would remove it and use explicit std:: qualification or narrow using declarations inside .cpp files or function bodies.
06

What are default arguments and what rules apply to them?

Save to ▾
Show answer
Default arguments supply values when a caller leaves out trailing arguments, for example void log(const std::string& msg, int level = 1);. Defaults must appear at the end of the parameter list and be given only once, usually in the header declaration. They are bound at compile time, so for a virtual function the default value comes from the static type of the pointer, not the dynamic type, which is a common trap.
07

What is the difference between struct and class in C++?

Save to ▾
Show answer
The only language difference is default access. Members and base classes of a struct are public by default, while in a class they are private by default. Both can have constructors, member functions, inheritance and templates. By convention a struct is used for simple data aggregates such as a Point, and a class is used for types that protect invariants with private state.
08

Compare pass by value, pass by pointer and pass by reference.

Save to ▾
Show answer
Pass by value copies the argument, so changes inside the function do not affect the caller. Pass by pointer passes an address, can be null and needs dereferencing. Pass by reference creates an alias that cannot be null and uses normal syntax. A good rule: pass small types such as int by value, large read-only objects by const reference, and use a non-const reference or pointer for output parameters.
09

Write a function to reverse a string in place without using std::reverse.

Save to ▾
Show answer
#include <string> #include <utility> void reverseInPlace(std::string& s) { if (s.empty()) return; std::size_t i = 0, j = s.size() - 1; while (i < j) { std::swap(s[i], s[j]); ++i; --j; } } // Two pointers meet in the middle: O(n) time, O(1) extra space.
10

Write an efficient function to check whether a number is prime.

Save to ▾
Show answer
bool isPrime(long long n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; for (long long i = 3; i * i <= n; i += 2) { if (n % i == 0) return false; } return true; } // Only odd divisors up to sqrt(n) are checked: O(sqrt n) time.
11

Write a swap function using references and explain why a pass-by-value version fails.

Save to ▾
Show answer
void swapByValue(int a, int b) { // works on copies, caller sees no change int t = a; a = b; b = t; } void swapByRef(int& a, int& b) { // a and b alias the caller's variables int t = a; a = b; b = t; } int x = 1, y = 2; swapByRef(x, y); // now x == 2, y == 1
12

Why did you choose C++ for your career instead of a language like Python or Java?

Save to ▾
Show answer
Situation: in college I built a small game and a file compressor in Python and hit performance limits. Task: I wanted to understand what happens closer to the hardware. Action: I learned C++ properly, including memory management, STL and multithreading, and rewrote the compressor. Result: it ran about ten times faster and I understood systems much better. I enjoy work where that control matters, while I still use Python for scripting.
13

A program that prints a million lines with std::endl is very slow. Why, and how do you fix it?

Save to ▾
Show answer
std::endl writes a newline and also flushes the stream buffer every time, forcing a system call per line. Replace it with the newline character so output is buffered and written in large chunks. For competitive programming or bulk output, also call std::ios::sync_with_stdio(false) and std::cin.tie(nullptr). Flush explicitly only when output must appear immediately, such as before a risky operation.
14

Explain the stages of compiling and running a C++ program.

Save to ▾
Show answer
There are four stages. The preprocessor expands #include directives and macros into a translation unit. The compiler turns each translation unit into assembly and then an object file. The linker combines object files and libraries and resolves symbols into an executable. At run time the loader maps it into memory. A missing function body therefore shows up as a linker error, not a compiler error.
15

What is the difference between const and constexpr?

Save to ▾
Show answer
const means a value cannot be modified after initialisation, but it may still be computed at run time. constexpr means the variable or function can be evaluated at compile time when its inputs are constant. With constexpr int sq(int x) { return x * x; } you can write int arr[sq(4)];. Use constexpr for array sizes, template arguments and lookup tables, and consteval when evaluation must happen at compile time.
16

What is function overloading and how does the compiler choose an overload?

Save to ▾
Show answer
Overloading means several functions share a name but differ in the number or types of parameters; return type alone is not enough. The compiler runs overload resolution: exact matches win, then promotions such as char to int, then standard conversions, then user-defined conversions. If two candidates are equally good the call is ambiguous and compilation fails. Name mangling gives every overload a unique linker symbol.
17

What does the static keyword mean in different contexts?

Save to ▾
Show answer
Inside a function, a static local variable is initialised once and keeps its value between calls. At namespace scope, static gives internal linkage, so the name is visible only in that translation unit. Inside a class, a static data member belongs to the class rather than each object, and a static member function has no this pointer. Since C++17 inline static members can be defined directly in the header.
18

What is the difference between an inline function and a macro?

Save to ▾
Show answer
A macro is text substitution done by the preprocessor with no type checking, so #define SQ(x) x*x gives a wrong result for SQ(a+1) and may evaluate arguments twice. An inline function is a real function with type checking, scope and debugger support, and the compiler may expand it at the call site. In modern C++ inline mainly allows a function to be defined in a header without breaking the One Definition Rule.
19

The linker reports undefined reference to a function that is declared in a header. What could be wrong?

Save to ▾
Show answer
The declaration exists but the linker finds no definition. Common causes: the .cpp file with the body is not compiled or not linked, the signature differs slightly such as const, namespace or parameter type, a template is defined in a .cpp file instead of the header, a C function is called without extern C linkage, or a library is missing from the link command or listed in the wrong order.
20

Two third-party libraries both define a global function called init and your build fails with duplicate symbols. How do you fix it?

Save to ▾
Show answer
The clean fix is to place each library's code in its own namespace so calls become liba::init and libb::init. If the source cannot change, I would check whether one function is only used internally and give it internal linkage, or wrap one library behind a shared library that hides its symbols using visibility settings. I avoid macro renaming hacks because they break silently on upgrades.
21

What are lvalues and rvalues?

Save to ▾
Show answer
An lvalue has identity and a persistent address, such as a named variable x. An rvalue is a temporary without lasting identity, such as 5 or the result of a + b. C++11 splits these further into lvalue, xvalue and prvalue. The distinction matters because rvalue references, written T&&, bind to temporaries and enable move semantics, letting the program steal resources instead of making expensive copies.
22

Write a C++ program that counts how often each word appears in the input.

Save to ▾
Show answer
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> freq; std::string word; while (std::cin >> word) { ++freq[word]; } for (const auto& [w, c] : freq) { std::cout << w << ' ' << c << '\n'; } } // Use std::unordered_map for O(1) average lookups if sorted output is not needed.
23

Tell me about a time you found a difficult bug in your C++ code.

Save to ▾
Show answer
Situation: a service crashed randomly about once a day in production. Task: find the root cause without blocking releases. Action: I enabled core dumps, analysed them in gdb and saw a corrupted vector inside a callback. A staging run with AddressSanitizer showed a use-after-free because a lambda captured a raw pointer to a destroyed object. I changed it to capture a weak_ptr. Result: no crashes for months, and sanitizer runs were added to CI.
24

What is undefined behaviour in C++? Give examples.

Save to ▾
Show answer
Undefined behaviour means the standard places no requirement on the result, so the program may crash, print garbage or appear to work. Examples are signed integer overflow, reading an uninitialised variable, out-of-bounds array access, dereferencing a null or dangling pointer and data races. Optimisers assume UB never happens and remove checks based on that, so such bugs often appear only in optimised release builds.
25

Your program gives correct output in a debug build but wrong output in a release build. How do you investigate?

Save to ▾
Show answer
This usually means undefined behaviour or an uninitialised variable that the optimiser exploits. I would compile with -Wall -Wextra and fix every warning, then run tests with -fsanitize=address,undefined to catch out-of-bounds access, overflow and use-after-free. ThreadSanitizer checks for data races. Building with -O2 -g lets me debug the optimised code, and bisecting functions or adding assertions narrows down the faulty spot.
26

What is a pointer and how is it different from a reference?

Save to ▾
Show answer
A pointer is a variable that stores a memory address; it can be null, can be reassigned and supports arithmetic. A reference is an alias for an existing object; it must be initialised, cannot be reseated to another object and cannot be null in valid code. Pointers suit optional values, arrays and dynamic memory, while references give clean syntax for parameters and operator overloading.
27

What is the difference between stack and heap memory?

Save to ▾
Show answer
Stack memory holds local variables and call frames; allocation is very fast and automatic, and memory is freed when the scope ends, but the size is limited to a few megabytes. Heap memory is allocated at run time with new or by containers, is much larger and lives until it is freed, but allocation is slower and can fragment. Large, variable-size or long-lived objects belong on the heap.
28

What is a dangling pointer?

Save to ▾
Show answer
A dangling pointer points to memory that has already been freed or has gone out of scope, for example the address of a local variable returned from a function, or a pointer used after delete. Dereferencing it is undefined behaviour and may crash much later in unrelated code. Prevent it with smart pointers, clear ownership rules and by never returning addresses of local variables.
29

What is pointer arithmetic?

Save to ▾
Show answer
Adding an integer to a pointer moves it by that many elements, not bytes, so p + 1 on an int* advances by sizeof(int) bytes. Subtracting two pointers into the same array gives the number of elements between them as ptrdiff_t. Arithmetic is only valid inside an array or one past its end; moving beyond that is undefined behaviour. Contiguous iterators work on the same idea.
30

What is the difference between delete and delete[]?

Save to ▾
Show answer
delete destroys a single object created with new. delete[] destroys an array created with new[] and calls the destructor of every element, using an element count the runtime stores with the allocation. Using delete on an array or delete[] on a single object is undefined behaviour and can leak or corrupt the heap. In modern code std::vector or std::unique_ptr<T[]> removes the need for either.
31

What is a void pointer and when would you use it?

Save to ▾
Show answer
A void* can hold the address of any object type but cannot be dereferenced or used in arithmetic until it is cast back to a real type. It appears in C APIs such as malloc, memcpy and callback user-data parameters. In C++ code, templates, std::any or std::variant are better because void* removes type safety and mistakes appear only at run time.
32

Find the middle node of a linked list in a single pass.

Save to ▾
Show answer
Node* middle(Node* head) { Node* slow = head; Node* fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } return slow; } // fast moves two steps and slow one step, so slow stops at the middle.
33

What is a memory leak and how do you detect one?

Save to ▾
Show answer
A leak happens when heap memory is allocated but never freed and the last pointer to it is lost, so memory use keeps growing. In long-running servers this eventually exhausts RAM. Detect leaks with Valgrind memcheck, LeakSanitizer through -fsanitize=address, or heap profilers. Prevent them with RAII types such as std::unique_ptr and std::vector, which release memory automatically.
34

What is the difference between new/delete and malloc/free?

Save to ▾
Show answer
new allocates memory and calls the constructor, returns a typed pointer and throws std::bad_alloc on failure. malloc only allocates raw bytes, returns void* and gives a null pointer on failure without calling any constructor. delete runs the destructor and then frees memory, while free does not run destructors. Never mix them, and always pair new[] with delete[].
35

What is RAII and why is it central to C++?

Save to ▾
Show answer
Resource Acquisition Is Initialization ties a resource's lifetime to an object's lifetime. The constructor acquires the resource, such as memory, a file, a socket or a mutex, and the destructor releases it. Because destructors run automatically when a scope ends, even when an exception is thrown, resources are never leaked. std::unique_ptr, std::lock_guard and std::fstream are standard RAII types.
36

Explain unique_ptr, shared_ptr and weak_ptr.

Save to ▾
Show answer
unique_ptr has sole ownership, cannot be copied, can only be moved, and costs almost nothing over a raw pointer. shared_ptr keeps a reference count in a control block and destroys the object when the last owner disappears. weak_ptr observes an object owned by shared_ptr without increasing the count; call lock() to get a shared_ptr if it still exists. weak_ptr breaks cycles and suits caches.
37

Why should you prefer make_unique and make_shared over calling new directly?

Save to ▾
Show answer
They avoid writing raw new, so no allocated object can leak if another expression in the same call throws. make_shared also allocates the object and the control block together in one allocation, which is faster and more cache friendly. One trade-off: with make_shared the memory block stays allocated until every weak_ptr is gone, which matters for very large objects.
38

Two objects hold shared_ptr references to each other and their memory is never released. Why, and how do you fix it?

Save to ▾
Show answer
This is a reference cycle. Each object keeps the other's reference count above zero, so neither destructor runs even after all outside pointers are gone. Fix it by making one direction non-owning, usually the back pointer, with weak_ptr. For example, a parent holds shared_ptr to its children, while each child holds a weak_ptr to the parent and calls lock() when it needs access.
39

What is the difference between const int*, int* const and const int* const?

Save to ▾
Show answer
Read the declaration from right to left. const int* p is a pointer to a const int: you cannot modify the value through p, but p can point elsewhere. int* const p is a const pointer to int: the address is fixed but the value can change. const int* const p fixes both the address and the value. These forms are frequent interview traps and appear in function signatures.
40

What is the difference between a shallow copy and a deep copy?

Save to ▾
Show answer
A shallow copy copies pointer members, so two objects share one heap buffer; destroying one leaves the other dangling and causes a double free. A deep copy allocates new memory and copies the contents. The compiler-generated copy constructor copies member by member, so a class owning a raw pointer needs a custom copy constructor and copy assignment, or better, should hold a std::vector or unique_ptr instead.
41

Reverse a singly linked list using pointers.

Save to ▾
Show answer
struct Node { int val; Node* next; }; Node* reverse(Node* head) { Node* prev = nullptr; while (head) { Node* nxt = head->next; head->next = prev; prev = head; head = nxt; } return prev; } // O(n) time, O(1) extra space.
42

Your program crashes with the message double free or corruption. What could cause it?

Save to ▾
Show answer
The same block was freed twice or heap metadata was overwritten. Typical causes are a class with a raw owning pointer and the default copy constructor, deleting the same pointer in two places, mixing delete and delete[], or a buffer overflow writing past an allocation. AddressSanitizer shows the first invalid free and where the memory was allocated. The lasting fix is clear ownership with smart pointers or containers.
43

A function returns a reference to a local variable and the code sometimes works. Explain what is happening.

Save to ▾
Show answer
The local is destroyed when the function returns, so the reference dangles and using it is undefined behaviour. It may seem to work because the old bytes remain on the stack until another call overwrites them. Compilers warn with -Wreturn-local-addr or -Wreturn-stack-address. The fix is to return by value; copy elision and move semantics make returning objects cheap.
44

Describe a time you improved code quality by changing how memory was managed.

Save to ▾
Show answer
Situation: our module used raw new and delete everywhere and QA reported frequent leaks. Task: make it safe without a full rewrite. Action: I proposed a step-by-step migration to unique_ptr and std::vector, wrote a one-page ownership guideline and enabled LeakSanitizer in CI so new leaks failed the build. Result: leak reports dropped to zero within two sprints and reviews became faster because ownership was obvious.
45

Write a function that allocates a 2D matrix safely without raw new and delete.

Save to ▾
Show answer
#include <vector> std::vector<std::vector<int>> makeMatrix(int rows, int cols) { return std::vector<std::vector<int>>(rows, std::vector<int>(cols, 0)); } // Faster single-block version: index with r * cols + c struct Matrix { int rows, cols; std::vector<int> data; Matrix(int r, int c) : rows(r), cols(c), data(r * c) {} int& at(int r, int c) { return data[r * cols + c]; } };
46

Implement a minimal unique_ptr-like class.

Save to ▾
Show answer
template <typename T> class UniquePtr { T* ptr_ = nullptr; public: explicit UniquePtr(T* p = nullptr) : ptr_(p) {} ~UniquePtr() { delete ptr_; } UniquePtr(const UniquePtr&) = delete; UniquePtr& operator=(const UniquePtr&) = delete; UniquePtr(UniquePtr&& o) noexcept : ptr_(o.ptr_) { o.ptr_ = nullptr; } UniquePtr& operator=(UniquePtr&& o) noexcept { if (this != &o) { delete ptr_; ptr_ = o.ptr_; o.ptr_ = nullptr; } return *this; } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } T* get() const { return ptr_; } };
47

A production service's memory usage grows steadily over several days. How do you find the cause?

Save to ▾
Show answer
First confirm it is a real leak and not a cache or allocator fragmentation by tracking RSS and allocator statistics. Then reproduce in staging with a heap profiler such as heaptrack or jemalloc profiling and compare snapshots to see which call stacks keep growing. LeakSanitizer catches lost blocks. Common culprits are unbounded maps, shared_ptr cycles and listeners never removed. After the fix, add a long soak test.
48

What are memory alignment and padding?

Save to ▾
Show answer
CPUs access data fastest at addresses that are multiples of its size, so the compiler aligns members and inserts padding bytes. A struct of char, int, char is usually 12 bytes, while ordering it as int, char, char gives 8. alignof reports alignment and alignas raises it, for example to 64 bytes to keep data used by different threads on separate cache lines. Packed structs save space but may be slower.
49

What is a custom deleter for a smart pointer and when do you need one?

Save to ▾
Show answer
A custom deleter tells the smart pointer how to release a resource that was not created with plain new. For example std::unique_ptr<FILE, decltype(&fclose)> f(fopen(path, mode), &fclose); closes the file automatically. Deleters are used for C library handles, sockets, OS handles and objects from custom pools. For unique_ptr the deleter is part of the type, while shared_ptr stores it in the control block.
50

What are placement new and memory pools?

Save to ▾
Show answer
Placement new constructs an object in memory you already own, written new (buffer) T(args). It does not allocate, so you must call the destructor yourself and release the buffer separately. A memory pool pre-allocates large blocks and hands out fixed-size slots, avoiding slow general-purpose allocation and fragmentation. Game engines, low-latency trading systems and std::pmr allocators use these for predictable performance.
51

Should a function take a shared_ptr by value, by const reference, or take a raw pointer or reference?

Save to ▾
Show answer
It depends on ownership. If the function only uses the object, take T& or T* and let the caller manage lifetime. Take shared_ptr by value only when the function stores or shares ownership, and then move it into place. Passing shared_ptr by value everywhere adds atomic reference count updates that slow down hot paths and hide who really owns the object.
52

What are the four pillars of object-oriented programming in C++?

Save to ▾
Show answer
Encapsulation hides data behind a class interface using private members and public methods. Abstraction exposes only what users need, often through abstract base classes. Inheritance lets a derived class reuse and extend a base class. Polymorphism lets one interface behave differently: compile-time through overloading and templates, run-time through virtual functions. Together they help model systems such as bank accounts, shapes or payment methods cleanly.
53

What kinds of constructors does C++ have?

Save to ▾
Show answer
A default constructor takes no arguments. A parameterised constructor takes arguments to initialise members. A copy constructor, T(const T&), creates an object from another of the same type. A move constructor, T(T&&), steals resources from a temporary. There are also delegating constructors that call another constructor and converting constructors that take one argument; mark those explicit to avoid unwanted implicit conversions.
54

What is a pure virtual function and an abstract class?

Save to ▾
Show answer
A pure virtual function is declared with = 0, such as virtual double area() const = 0;, and has no required implementation in the base. A class with at least one pure virtual function is abstract and cannot be instantiated; it only defines an interface. Derived classes must override every pure virtual function to become concrete. This is how C++ expresses interfaces like Shape or PaymentGateway.
55

What is the difference between overloading and overriding, and what do override and final do?

Save to ▾
Show answer
Overloading means same name, different parameters, resolved at compile time within one scope. Overriding means a derived class replaces a base virtual function with the same signature, resolved at run time. The override keyword makes the compiler check that a matching base virtual exists, catching typos and const mismatches. final stops further overriding of a function or further inheritance from a class.
56

Write a Shape hierarchy with a virtual area function and use it polymorphically.

Save to ▾
Show answer
#include <iostream> #include <memory> #include <vector> struct Shape { virtual ~Shape() = default; virtual double area() const = 0; }; struct Circle : Shape { double r; explicit Circle(double r) : r(r) {} double area() const override { return 3.14159 * r * r; } }; struct Rect : Shape { double w, h; Rect(double w, double h) : w(w), h(h) {} double area() const override { return w * h; } }; int main() { std::vector<std::unique_ptr<Shape>> v; v.push_back(std::make_unique<Circle>(2)); v.push_back(std::make_unique<Rect>(3, 4)); for (const auto& s : v) std::cout << s->area() << '\n'; }
57

How would you explain polymorphism to a junior developer who has just joined your team?

Save to ▾
Show answer
Situation: a new joiner was confused by virtual functions in our codebase. Task: help them become productive quickly. Action: I used a real example from our code, a Notifier base class with Email and Sms versions, drew how the vtable decides the call at run time, and gave them a small task to add a WhatsApp notifier. Result: they finished it in a day and later explained the idea to the next intern.
58

Explain the rule of three, rule of five and rule of zero.

Save to ▾
Show answer
Rule of three: if a class needs a custom destructor, copy constructor or copy assignment, it usually needs all three because it manages a resource. Rule of five adds the move constructor and move assignment from C++11. Rule of zero says the best design avoids writing any of them by holding resources in members such as std::vector, std::string and unique_ptr, which already manage themselves.
59

How do virtual functions work internally?

Save to ▾
Show answer
Most compilers give each polymorphic class a vtable, a static table of function pointers for its virtual functions. Every object stores a hidden vptr pointing to its class's vtable. A call through a base pointer loads the vptr, looks up the slot and jumps to the right override. The cost is one pointer per object, an indirect call and usually no inlining, which matters only in very hot loops.
60

Why should a base class have a virtual destructor?

Save to ▾
Show answer
If you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs, which is undefined behaviour and typically leaks the derived part's resources. Making the destructor virtual ensures the derived destructor runs first, then the base one. Rule: any class meant to be used polymorphically needs a public virtual destructor, or a protected non-virtual one.
61

What is object slicing?

Save to ▾
Show answer
Slicing happens when a derived object is copied into a base object by value. Only the base part is copied, the derived data is lost and virtual calls use the base version. Example: void draw(Shape s) called with a Circle loses Circle's radius and behaviour. Avoid it by passing polymorphic objects by reference or pointer, and consider deleting copy operations in polymorphic base classes.
62

Memory leaks appear when derived objects stored as Base* are deleted. What is wrong and how do you fix it?

Save to ▾
Show answer
The base class almost certainly has a non-virtual destructor, so delete through a Base* runs only the base destructor and the derived members, such as buffers or file handles, are never released. Add virtual ~Base() = default; to the base. Better still, store the objects as std::unique_ptr<Base> so deletion is automatic, and enable -Wdelete-non-virtual-dtor to catch this at compile time.
63

Design a class structure for UPI, card and net banking payments in a checkout system.

Save to ▾
Show answer
I would define an abstract PaymentMethod interface with virtual functions such as authorize, capture, refund and a virtual destructor. UpiPayment, CardPayment and NetBankingPayment implement it with their own validation. Checkout depends only on PaymentMethod, and a factory creates the right object from user choice. New methods such as wallets can be added without touching checkout code, which follows the open-closed principle.
64

Should a Car class inherit from Engine or contain an Engine? Explain your choice.

Save to ▾
Show answer
A car is not an engine, it has an engine, so composition is correct: class Car holds an Engine member or a unique_ptr<Engine>. Inheritance models an is-a relationship and exposes the base interface, which would let callers treat a Car as an Engine. Composition also allows swapping engine types at run time through an interface such as PetrolEngine or ElectricMotor and keeps coupling low.
65

A function taking a Money object is silently called with an int and gives wrong results. What is happening?

Save to ▾
Show answer
Money probably has a single-argument constructor such as Money(int paise) that is not marked explicit, so the compiler performs an implicit conversion from int. A call like pay(500) compiles even though the unit is unclear. Mark single-argument constructors explicit, so callers must write pay(Money(500)). Also consider strong types or named factory functions like Money::fromRupees to make units obvious.
66

Overload operator+ and operator<< for a Complex number class.

Save to ▾
Show answer
#include <ostream> class Complex { double re_, im_; public: Complex(double re = 0, double im = 0) : re_(re), im_(im) {} Complex operator+(const Complex& o) const { return Complex(re_ + o.re_, im_ + o.im_); } friend std::ostream& operator<<(std::ostream& os, const Complex& c) { return os << c.re_ << (c.im_ < 0 ? '-' : '+') << (c.im_ < 0 ? -c.im_ : c.im_) << 'i'; } }; // operator<< is a friend non-member so the stream stays on the left side.
67

Implement a thread-safe singleton in modern C++.

Save to ▾
Show answer
class Config { public: static Config& instance() { static Config inst; // initialised once, thread-safe since C++11 return inst; } Config(const Config&) = delete; Config& operator=(const Config&) = delete; private: Config() = default; }; // The Meyers singleton relies on magic statics; no mutex or double-checked locking needed.
68

Tell me about a time you designed the class structure for a module and how you handled review feedback.

Save to ▾
Show answer
Situation: I had to build a report export module supporting PDF, CSV and Excel. Task: design it so new formats were easy to add. Action: I proposed an abstract Exporter interface and a factory, shared a short design note and asked seniors to review before coding. They pointed out duplicated formatting logic, so I extracted a Formatter helper. Result: a fourth format was later added in one day with no changes to existing classes.
69

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

Save to ▾
Show answer
When B and C both inherit from A and D inherits from B and C, D contains two copies of A, so accessing A's members is ambiguous. Declaring class B : virtual public A and class C : virtual public A makes D share a single A subobject. The most-derived class then initialises A directly. Virtual inheritance adds pointer overhead, so it is used sparingly, usually for interface-like bases.
70

You call a virtual function from a base class constructor but the derived override never runs. Why?

Save to ▾
Show answer
During base construction the derived part does not exist yet, so the object's dynamic type is the base and the vptr points to the base vtable. Virtual calls in constructors and destructors therefore go to the version of the class currently being built. Calling a pure virtual this way is undefined. Fix it with a two-phase init method called after construction or a factory function that constructs and then configures.
71

You inherit a 3000-line class that handles parsing, validation, database and logging. How would you refactor it?

Save to ▾
Show answer
It breaks the single responsibility principle. First I add characterisation tests around current behaviour. Then I extract cohesive pieces into separate classes such as Parser, Validator and Repository, injected through interfaces so they can be mocked. I move step by step, keeping the old public API as a facade, and merge small refactors frequently instead of one big rewrite, so risk stays low and reviews stay easy.
72

A hot loop calls a virtual function millions of times and profiling shows the indirect call cost. What can you do?

Save to ▾
Show answer
Options include static polymorphism with CRTP or templates so calls can be inlined, marking classes or functions final so the compiler can devirtualise, and batching work by type so each loop handles one concrete class. Another option is replacing the hierarchy with std::variant and std::visit. I would confirm with a benchmark first, because often memory layout matters more than the virtual call itself.
73

Implement a simple String class that follows the rule of five.

Save to ▾
Show answer
#include <cstring> #include <utility> class String { char* data_ = nullptr; std::size_t len_ = 0; public: String(const char* s = "") : len_(std::strlen(s)) { data_ = new char[len_ + 1]; std::memcpy(data_, s, len_ + 1); } ~String() { delete[] data_; } String(const String& o) : String(o.data_) {} String(String&& o) noexcept : data_(std::exchange(o.data_, nullptr)), len_(std::exchange(o.len_, 0)) {} String& operator=(String o) noexcept { // copy-and-swap handles both std::swap(data_, o.data_); std::swap(len_, o.len_); return *this; } const char* c_str() const { return data_ ? data_ : ""; } };
74

Implement a basic Observer pattern for an event publisher.

Save to ▾
Show answer
#include <functional> #include <string> #include <vector> class EventBus { public: using Handler = std::function<void(const std::string&)>; int subscribe(Handler h) { handlers_.push_back({nextId_, std::move(h)}); return nextId_++; } void unsubscribe(int id) { std::erase_if(handlers_, [id](const auto& p) { return p.first == id; }); } void publish(const std::string& msg) const { for (const auto& [id, h] : handlers_) h(msg); } private: std::vector<std::pair<int, Handler>> handlers_; int nextId_ = 0; };
75

Show the copy-and-swap idiom and explain why it gives strong exception safety.

Save to ▾
Show answer
class Buffer { std::size_t n_; int* p_; public: explicit Buffer(std::size_t n) : n_(n), p_(new int[n]{}) {} Buffer(const Buffer& o) : n_(o.n_), p_(new int[o.n_]) { std::copy(o.p_, o.p_ + n_, p_); } ~Buffer() { delete[] p_; } friend void swap(Buffer& a, Buffer& b) noexcept { std::swap(a.n_, b.n_); std::swap(a.p_, b.p_); } Buffer& operator=(Buffer other) noexcept { // copy made before we touch *this swap(*this, other); return *this; } }; // If the copy throws, *this is unchanged; self-assignment is safe too.
76

Describe a situation where you disagreed with a senior engineer about a design decision.

Save to ▾
Show answer
Situation: a senior wanted a deep inheritance hierarchy for device drivers. Task: I believed composition would be simpler to test. Action: instead of arguing in the meeting, I built a small prototype of both designs, measured test setup effort and shared the results calmly, while accepting that the final call was theirs. Result: we chose a hybrid with a thin interface plus composition, and the senior later asked me to document it for the team.
77

What are templates in C++? Explain function and class templates.

Save to ▾
Show answer
Templates let you write code once for many types; the compiler generates a concrete version for each type used. A function template such as template <typename T> T maxOf(T a, T b) works for int, double or std::string. A class template such as template <typename T> class Stack builds containers for any element type. The whole STL, including vector, map and algorithms, is built on templates.
78

What are non-type template parameters?

Save to ▾
Show answer
Template parameters can be values, not just types, as long as they are compile-time constants, such as integers, enums, pointers and, since C++20, some class types. std::array<int, 5> uses a size parameter. Example: template <int N> int power(int x) can be unrolled by the compiler. Each different value creates a separate instantiation, so they suit small fixed sets of values.
79

Write a generic function template that returns the larger of two values.

Save to ▾
Show answer
template <typename T> const T& maxOf(const T& a, const T& b) { return (a < b) ? b : a; } // usage int m = maxOf(3, 7); // T = int double d = maxOf(2.5, 1.5); // T = double auto s = maxOf<double>(3, 4.5); // explicit T avoids deduction conflict
80

Implement a generic Stack class template backed by std::vector.

Save to ▾
Show answer
#include <stdexcept> #include <vector> template <typename T> class Stack { std::vector<T> items_; public: void push(const T& x) { items_.push_back(x); } void push(T&& x) { items_.push_back(std::move(x)); } void pop() { if (items_.empty()) throw std::out_of_range("empty stack"); items_.pop_back(); } const T& top() const { return items_.back(); } bool empty() const { return items_.empty(); } std::size_t size() const { return items_.size(); } };
81

Compute a factorial at compile time.

Save to ▾
Show answer
constexpr unsigned long long factorial(unsigned n) { unsigned long long r = 1; for (unsigned i = 2; i <= n; ++i) r *= i; return r; } static_assert(factorial(5) == 120); constexpr auto f10 = factorial(10); // computed by the compiler // Pre-C++14 style used template recursion: // template <unsigned N> struct Fact { static const unsigned long long v = N * Fact<N - 1>::v; }; // template <> struct Fact<0> { static const unsigned long long v = 1; };
82

How do you keep your C++ knowledge up to date with new standards?

Save to ▾
Show answer
Situation: I noticed many tutorials still teach C++98 style. Task: learn modern practices properly. Action: I follow cppreference for each new standard, watch selected conference talks, read the C++ Core Guidelines and try features such as concepts, ranges and std::format in small practice projects compiled with recent GCC and Clang. Result: I can explain when a modern feature helps and when older code is fine.
83

Why are templates usually defined in header files?

Save to ▾
Show answer
A template is only a pattern; code is generated when it is instantiated with concrete types, and the compiler must see the full definition at that point. If the body lives in a .cpp file, other translation units cannot instantiate it and you get linker errors. The usual fix is defining templates in headers, or using explicit instantiation in the .cpp for a known, fixed set of types.
84

What is the difference between full and partial template specialization?

Save to ▾
Show answer
Full specialization provides a separate implementation for one exact set of template arguments, such as template <> class Hash<std::string>. Partial specialization, allowed only for class and variable templates, covers a family of arguments, such as template <typename T> class Hash<T*> for all pointer types. Function templates cannot be partially specialised; overloading is used instead.
85

What are C++20 concepts?

Save to ▾
Show answer
Concepts are named compile-time predicates on template parameters. You can write template <std::integral T> T gcd(T a, T b) or define your own with a requires expression. If a type does not satisfy the concept, the compiler reports a short, readable error at the call site instead of pages of instantiation errors. Concepts also allow overloading by constraint and document the template's expectations.
86

When do you need the typename keyword inside a template?

Save to ▾
Show answer
Inside a template, a name that depends on a template parameter, such as T::value_type, could be a type or a static member, so the compiler assumes it is a value. You must write typename T::value_type x; to say it is a type. Similarly, a dependent member template needs the template keyword, as in obj.template get<0>(). C++20 relaxes this in some contexts, but the rule still matters.
87

What are type traits and how does if constexpr use them?

Save to ▾
Show answer
Type traits in <type_traits> answer questions about types at compile time, such as std::is_integral_v<T>, std::is_pointer_v<T> or std::is_same_v<T, U>, and transform types, such as std::remove_reference_t. if constexpr picks a branch at compile time and discards the other, so code like if constexpr (std::is_integral_v<T>) can call integer-only operations safely inside a generic function.
88

What is template argument deduction and class template argument deduction?

Save to ▾
Show answer
For function templates the compiler deduces T from the call, so maxOf(3, 7) deduces int; mixing int and double fails because T would be ambiguous. Class template argument deduction, added in C++17, lets you write std::vector v{1, 2, 3}; or std::pair p(1, 2.5); without spelling the template arguments. Deduction guides can be written to tell the compiler how to deduce types from constructors.
89

A teammate complains that a template function produces hundreds of lines of compiler errors when misused. How do you improve this?

Save to ▾
Show answer
Constrain the template so misuse fails early with a clear message. With C++20 I would add a concept or requires clause, for example template <std::totally_ordered T>, so the error names the unmet requirement at the call site. On older standards, a static_assert with a readable message at the top of the function body helps. Good naming and a comment on expected type properties also help.
90

A generic average function must accept only numeric types. How would you enforce that?

Save to ▾
Show answer
In C++20 I would constrain it: template <typename T> requires std::is_arithmetic_v<T> double average(const std::vector<T>& v). Passing a vector of strings then fails with a clear constraint error. On C++17 the same check can go in a static_assert or std::enable_if. I would also decide whether bool and char should be allowed, since they are technically arithmetic types.
91

You need a container that holds ints, strings and doubles together. Which approach would you choose?

Save to ▾
Show answer
If the set of types is fixed and known, std::vector<std::variant<int, std::string, double>> is type-safe and needs no heap per element; std::visit handles each type. If types are open-ended, std::any works but needs any_cast and loses compile-time checks. If the items share behaviour, a base class interface with unique_ptr is cleanest. I usually prefer variant for closed sets.
92

A generic maxOf template gives wrong results when called with two C-style string literals. Why, and how do you fix it?

Save to ▾
Show answer
T is deduced as const char*, so the template compares pointer addresses instead of the characters. The result depends on where the literals are stored. Fix it by adding an overload for const char* that uses std::strcmp, or better, call it with std::string or std::string_view, where operator< compares contents. This shows why generic code must consider what operations mean for each type.
93

Write a variadic function that sums any number of arguments and one that prints them.

Save to ▾
Show answer
#include <iostream> template <typename... Args> auto sum(Args... args) { return (args + ...); // unary right fold } template <typename... Args> void printAll(const Args&... args) { ((std::cout << args << ' '), ...); // comma fold std::cout << '\n'; } // sum(1, 2, 3.5) returns 6.5; printAll(1, 'x', 2.5) prints 1 x 2.5
94

Write a C++20 concept and use it to constrain a function.

Save to ▾
Show answer
#include <concepts> #include <string> template <typename T> concept Printable = requires(T t) { { t.toString() } -> std::convertible_to<std::string>; }; template <Printable T> std::string describe(const T& obj) { return "Item: " + obj.toString(); } struct User { std::string name; std::string toString() const { return name; } }; // describe(User{"Asha"}) compiles; describe(42) fails with a clear message.
95

Tell me about a time you wrote generic, reusable code that saved effort for your team.

Save to ▾
Show answer
Situation: three services each had their own copy of retry logic for network calls. Task: remove duplication without slowing them down. Action: I wrote a small header-only template, retry with a callable and a policy for attempts and backoff, added unit tests and documented examples. Result: all three services adopted it, around 600 lines of duplicate code were deleted and a bug fix now happens in one place.
96

What are variadic templates and fold expressions?

Save to ▾
Show answer
A variadic template accepts any number of template arguments using a parameter pack, written template <typename... Args>. Before C++17 packs were processed recursively. Fold expressions from C++17 apply an operator across the whole pack in one line, for example return (args + ...); sums all arguments. They power std::make_unique, std::tuple, std::format and logging functions that take arbitrary arguments.
97
Save to ▾
Show answer
Substitution Failure Is Not An Error: when the compiler substitutes template arguments and the resulting declaration is invalid, that candidate is silently removed from overload resolution instead of causing an error. It was traditionally used with std::enable_if to enable functions only for certain types, such as integral types. In C++20, concepts and requires clauses replace most SFINAE tricks with clearer syntax and error messages.
98

The release binary has grown very large and analysis shows many template instantiations. What can you do?

Save to ▾
Show answer
Each distinct set of template arguments generates separate code, so heavy generic code bloats binaries. I would find the biggest symbols with tools like bloaty or nm, move type-independent logic into a non-template base or helper, use type erasure for rarely hot paths, limit instantiations with extern template, and enable link-time optimisation plus identical code folding to merge duplicate functions.
99

Build times have become very slow because heavy templates are included everywhere. How do you speed them up?

Save to ▾
Show answer
I would measure first with -ftime-trace or build analyzers to find the costly headers. Then reduce includes with forward declarations, move template-heavy implementation details behind non-template interfaces, use extern template with explicit instantiation for common types, enable precompiled headers and a compiler cache such as ccache, and evaluate C++20 modules where the toolchain supports them well.
100

How do you decide between templates and virtual functions for polymorphism?

Save to ▾
Show answer
Templates give static polymorphism: resolved at compile time, inlinable and fast, but types must be known at compile time and code size grows. Virtual functions give dynamic polymorphism: one compiled body, types can be chosen at run time, plugins are possible, at the cost of an indirect call. I use templates for performance-critical generic algorithms and virtual interfaces for runtime-configurable components.
101

Implement your own is_pointer type trait.

Save to ▾
Show answer
template <typename T> struct IsPointer { static constexpr bool value = false; }; template <typename T> struct IsPointer<T*> { // partial specialization for pointers static constexpr bool value = true; }; template <typename T> inline constexpr bool IsPointer_v = IsPointer<T>::value; static_assert(IsPointer_v<int*>); static_assert(!IsPointer_v<int>); // The real std::is_pointer also strips const and volatile first.
102

What are the main components of the Standard Template Library?

Save to ▾
Show answer
The STL has four parts. Containers store data, such as vector, deque, list, map, set and unordered_map. Iterators give a uniform way to traverse containers. Algorithms such as sort, find, accumulate and lower_bound work on iterator ranges. Function objects and lambdas customise algorithms, for example a comparator for sort. Adapters such as stack, queue and priority_queue wrap other containers.
103

Compare std::vector, std::list and std::deque.

Save to ▾
Show answer
vector stores elements contiguously, gives O(1) random access and fast iteration, with amortised O(1) push_back but O(n) insertion in the middle. list is a doubly linked list with O(1) insert and erase anywhere given an iterator, but no random access and poor cache use. deque supports fast insertion at both ends and random access, stored in chunks. Default to vector unless profiling says otherwise.
104

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

Save to ▾
Show answer
std::map is usually a red-black tree: keys are kept sorted and lookup, insert and erase are O(log n). std::unordered_map is a hash table with average O(1) operations but no ordering, and worst case O(n) with many collisions. Use map when you need ordered iteration or range queries like lower_bound, and unordered_map for fast key lookups where order does not matter.
105

Sort a vector of pairs by the second value in descending order, breaking ties by the first value.

Save to ▾
Show answer
#include <algorithm> #include <vector> std::vector<std::pair<int, int>> v = {{1, 5}, {2, 3}, {3, 5}}; std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) { if (a.second != b.second) return a.second > b.second; return a.first < b.first; }); // Result: {1,5} {3,5} {2,3}. The comparator must be a strict weak ordering.
106

Solve two sum: return indices of two numbers that add up to a target.

Save to ▾
Show answer
#include <unordered_map> #include <vector> std::vector<int> twoSum(const std::vector<int>& nums, int target) { std::unordered_map<int, int> seen; // value -> index for (int i = 0; i < static_cast<int>(nums.size()); ++i) { auto it = seen.find(target - nums[i]); if (it != seen.end()) return {it->second, i}; seen[nums[i]] = i; } return {}; } // O(n) time, O(n) space.
107

Remove duplicates from a vector of integers.

Save to ▾
Show answer
#include <algorithm> #include <vector> void dedupSorted(std::vector<int>& v) { std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end()); } // O(n log n). std::unique only removes adjacent duplicates, so sort first. // To keep the original order, track seen values in an unordered_set instead.
108

Describe a time you had to learn a new library or API quickly.

Save to ▾
Show answer
Situation: during my internship I was asked to fix a bug in code using Boost.Asio, which I had never used. Task: understand enough to fix it within the sprint. Action: I read the official examples, wrote a tiny echo server to learn the async model, then traced the bug to a missing handler for connection timeouts. Result: I fixed it in four days and wrote a short internal note for the next new joiner.
109

When are std::vector iterators invalidated?

Save to ▾
Show answer
Any insertion that causes reallocation, when size exceeds capacity, invalidates all iterators, pointers and references. Insertion without reallocation invalidates those at or after the insertion point. erase invalidates iterators at and after the erased element. clear and resize to a larger size beyond capacity invalidate everything. Holding a pointer to an element and then calling push_back is a classic bug.
110

How does std::vector grow, and what is the difference between size, capacity and reserve?

Save to ▾
Show answer
size is the number of stored elements; capacity is how many fit before reallocation. When push_back exceeds capacity, vector allocates a larger buffer, typically 1.5 or 2 times larger, moves or copies elements and frees the old one, giving amortised O(1) appends. reserve(n) pre-allocates capacity to avoid repeated reallocations when the final size is known; shrink_to_fit requests releasing unused capacity.
111

What is the difference between push_back and emplace_back?

Save to ▾
Show answer
push_back takes an existing object, copying or moving it into the container. emplace_back forwards constructor arguments and builds the element directly in place, which can avoid a temporary. For example v.emplace_back(name, age) constructs a Person inside the vector. The gain is small when you already have an object, and emplace_back can call explicit constructors unexpectedly, so use it deliberately.
112

What are the iterator categories in C++?

Save to ▾
Show answer
Input and output iterators support a single pass, such as stream iterators. Forward iterators allow multiple passes, as in forward_list. Bidirectional iterators also move backwards, as in list, map and set. Random access iterators support jumps and arithmetic, as in vector and deque, and C++20 adds contiguous iterators. Algorithms require a minimum category, so std::sort needs random access and cannot sort a std::list.
113

When would you use std::set versus std::priority_queue?

Save to ▾
Show answer
priority_queue is a binary heap that gives O(1) access to the largest element and O(log n) push and pop, but you cannot search or erase arbitrary elements. std::set keeps all elements sorted with O(log n) insert, erase and find, and gives both minimum and maximum. Use priority_queue for schedulers and Dijkstra, and set or multiset when you must update or remove arbitrary items.
114

What is the erase-remove idiom and what replaced it in C++20?

Save to ▾
Show answer
std::remove does not delete elements; it shifts the kept elements forward and returns an iterator to the new logical end. You then call erase to shrink the container: v.erase(std::remove(v.begin(), v.end(), 0), v.end());. remove_if works the same with a predicate. C++20 adds std::erase(v, value) and std::erase_if(v, pred), which do both steps in one call.
115

A program does millions of lookups in a std::map with string keys and is slow. How would you speed it up?

Save to ▾
Show answer
If ordering is not needed, switch to std::unordered_map and call reserve with the expected size to avoid rehashing. For string keys, use heterogeneous lookup with string_view to avoid building temporary strings. If keys are fixed after loading, a sorted vector with binary search is very cache friendly. I would profile before and after, because hashing long strings has its own cost.
116

Using a custom struct as the key of an unordered_map gives a compile error. Why, and how do you fix it?

Save to ▾
Show answer
unordered_map needs a hash function and equality comparison for the key type, and std::hash is not defined for user structs. Fix it by defining operator== (or defaulting it in C++20) and providing a hash functor that combines member hashes, passed as the third template argument, or by specialising std::hash for the type. std::map instead needs operator< or a comparator.
117

Code that erases elements from a vector inside a range-based for loop crashes. Why, and what is the correct way?

Save to ▾
Show answer
erase invalidates the iterator being used by the loop, so the next increment is undefined behaviour. Range-based for loops cannot handle this safely. Use the iterator returned by erase: for (auto it = v.begin(); it != v.end();) { if (bad(*it)) it = v.erase(it); else ++it; }. Better still, use std::erase_if, which is O(n) overall instead of O(n squared) for repeated erases.
118

Sorting a vector of large objects is slow. What can you do?

Save to ▾
Show answer
Sorting moves elements many times, so large objects that copy instead of move are expensive. First ensure the type has a noexcept move constructor. If moves are still heavy, sort a vector of indices or pointers with a comparator on the key, then reorder once if needed. Precomputing the sort key avoids repeated expensive comparisons. Use std::stable_sort only when equal-element order matters.
119

Write a custom hash so a struct can be used as a key in std::unordered_map.

Save to ▾
Show answer
#include <functional> #include <string> #include <unordered_map> struct Point { int x, y; bool operator==(const Point&) const = default; }; struct PointHash { std::size_t operator()(const Point& p) const noexcept { std::size_t h1 = std::hash<int>{}(p.x); std::size_t h2 = std::hash<int>{}(p.y); return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); } }; std::unordered_map<Point, std::string, PointHash> grid;
120

Group a list of words into anagram groups.

Save to ▾
Show answer
#include <algorithm> #include <string> #include <unordered_map> #include <vector> std::vector<std::vector<std::string>> groupAnagrams(const std::vector<std::string>& words) { std::unordered_map<std::string, std::vector<std::string>> groups; for (const auto& w : words) { std::string key = w; std::sort(key.begin(), key.end()); groups[key].push_back(w); } std::vector<std::vector<std::string>> out; for (auto& [k, g] : groups) out.push_back(std::move(g)); return out; } // O(n * k log k) where k is the word length.
121

Tell me about a time when choosing a better data structure improved performance.

Save to ▾
Show answer
Situation: a pricing job took 40 minutes because it searched a vector of 2 lakh products linearly for every order line. Task: bring it under 5 minutes without changing output. Action: I profiled with perf, confirmed the hot loop, replaced the search with an unordered_map keyed by product ID built once with reserve, and added a regression test. Result: the job finished in about 3 minutes and the team adopted profiling before optimising.
122

You need to build an LRU cache with O(1) get and put. Which containers would you use?

Save to ▾
Show answer
Combine a doubly linked list with a hash map. std::list stores key-value pairs in usage order, with the most recent at the front. std::unordered_map maps each key to its list iterator. On get, splice the node to the front in O(1). On put, update or insert at the front and, if over capacity, remove the back node and its map entry. list iterators stay valid after splice, which makes this work.
123

You must find the top 100 most frequent items in a stream of 10 million events. How would you do it?

Save to ▾
Show answer
Count frequencies with an unordered_map reserved to the expected key count. Then keep a min-heap, a priority_queue with greater comparator, of size 100: push each entry and pop when size exceeds 100, which costs O(n log k). Alternatively copy counts into a vector and use std::nth_element for O(n) average. If memory is limited and approximate results are fine, a Count-Min sketch helps.
124

Code that takes bool& from a std::vector<bool> fails to compile. Why?

Save to ▾
Show answer
std::vector<bool> is a special case that packs bits, so elements are not real bool objects and operator[] returns a proxy object, not bool&. You cannot take a reference or pointer to a single element, and it is not thread-safe to write neighbouring elements from different threads. If you need real bools use std::vector<char>, std::deque<bool>, or std::bitset when the size is fixed.
125

Implement an LRU cache with get and put in O(1).

Save to ▾
Show answer
#include <list> #include <unordered_map> class LRUCache { int cap_; std::list<std::pair<int, int>> items_; // front = most recent std::unordered_map<int, std::list<std::pair<int, int>>::iterator> pos_; public: explicit LRUCache(int capacity) : cap_(capacity) {} int get(int key) { auto it = pos_.find(key); if (it == pos_.end()) return -1; items_.splice(items_.begin(), items_, it->second); return it->second->second; } void put(int key, int value) { if (auto it = pos_.find(key); it != pos_.end()) { it->second->second = value; items_.splice(items_.begin(), items_, it->second); return; } if (static_cast<int>(items_.size()) == cap_) { pos_.erase(items_.back().first); items_.pop_back(); } items_.emplace_front(key, value); pos_[key] = items_.begin(); } };
126

Tell me about a code review where you pointed out an important issue in a colleague's code.

Save to ▾
Show answer
Situation: a colleague's change stored pointers to vector elements in a map and then appended to the vector. Task: flag the risk without discouraging them. Action: I commented with a short example showing reallocation invalidating the pointers, suggested storing indices or using std::deque, and offered to pair on the fix. Result: the bug was fixed before release, and we added a checklist item on iterator invalidation for reviews.
127

What do auto and decltype do?

Save to ▾
Show answer
auto deduces a variable's type from its initialiser, so auto it = m.begin(); avoids long iterator types. It drops top-level const and references unless you write const auto& or auto&. decltype(expr) yields the declared type of an expression without evaluating it, useful in generic code and return types. decltype(auto) keeps reference-ness exactly, which matters when forwarding return values.
128

What are lambdas and how do capture modes work?

Save to ▾
Show answer
A lambda is an unnamed function object written inline, for example [](int a, int b) { return a < b; }. The capture list decides what outside variables it can use: [x] copies x, [&x] references x, [=] copies everything used, [&] references everything used, and [this] captures the object pointer. C++14 allows init captures such as [p = std::move(ptr)]. Reference captures dangle if the lambda outlives the variables.
129

Why use nullptr instead of NULL or 0?

Save to ▾
Show answer
NULL is usually defined as 0 or 0L, an integer, so overloaded functions such as f(int) and f(char*) pick the int version for f(NULL), which surprises readers. nullptr has its own type, std::nullptr_t, that converts only to pointer types, so f(nullptr) calls the pointer overload. It also works correctly in templates where the type is deduced. Modern code should always use nullptr.
130

What are structured bindings and how do they work with range-based for loops?

Save to ▾
Show answer
Structured bindings, from C++17, unpack a pair, tuple, array or simple struct into named variables: auto [id, name] = getUser();. In loops they make map iteration readable: for (const auto& [key, value] : m). The variables are aliases into a hidden object, so const auto& avoids copies. They pair well with if statements with initialisers, such as if (auto [it, ok] = s.insert(x); ok).
131

Use lambdas with standard algorithms to sort strings by length and count those longer than a limit.

Save to ▾
Show answer
#include <algorithm> #include <string> #include <vector> std::vector<std::string> names = {"Ravi", "Anjali", "Om", "Priyanka"}; std::size_t limit = 4; std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); }); auto longCount = std::count_if(names.begin(), names.end(), [limit](const std::string& s) { return s.size() > limit; }); // names: Om, Ravi, Anjali, Priyanka; longCount == 2
132

Write a lookup function that uses std::optional instead of returning -1 or a null pointer.

Save to ▾
Show answer
#include <optional> #include <string> #include <unordered_map> std::optional<int> findAge(const std::unordered_map<std::string, int>& db, const std::string& name) { if (auto it = db.find(name); it != db.end()) return it->second; return std::nullopt; } // caller if (auto age = findAge(db, "Meera")) { use(*age); } int a = findAge(db, "Unknown").value_or(0);
133

Show how std::format and std::print format output in modern C++.

Save to ▾
Show answer
#include <format> #include <print> // C++23 #include <string> std::string name = "Kiran"; double score = 92.456; std::string line = std::format("{} scored {:.1f}%", name, score); // C++20 std::print("{:<10}|{:>8.2f}\n", name, score); // C++23 std::string hex = std::format("{:#x}", 255); // 0xff // Type-safe like iostreams, readable like printf, and checked at compile time.
134

Explain move semantics and what std::move actually does.

Save to ▾
Show answer
Move semantics let an object transfer its resources, such as a heap buffer, to another object instead of copying them. A move constructor takes T&& and usually steals the pointer and leaves the source empty but valid. std::move does not move anything; it is just a cast to an rvalue reference that allows a move overload to be chosen. After moving, only assign to or destroy the source.
135

What are std::optional, std::variant and std::any?

Save to ▾
Show answer
std::optional<T> holds either a T or nothing, ideal for functions that may not return a value, without using magic values or pointers. std::variant<A, B> is a type-safe union that holds exactly one of the listed types, inspected with std::visit or std::get_if. std::any holds a value of any copyable type and needs any_cast to read it. Prefer optional and variant because they are checked at compile time.
136

What does the C++20 ranges library add?

Save to ▾
Show answer
Ranges let algorithms take whole containers, as in std::ranges::sort(v), instead of begin and end pairs. Views such as filter, transform, take and reverse are lazy and compose with the pipe operator, for example v | std::views::filter(isEven) | std::views::transform(square). Nothing is computed until you iterate. Ranges also use concepts, so errors are clearer, and projections let you sort by a member easily.
137

What is std::string_view and what are its pitfalls?

Save to ▾
Show answer
string_view is a non-owning pointer and length pair that refers to existing characters, so passing it avoids copies and accepts both std::string and literals. The main pitfall is lifetime: it must not outlive the data it views, so returning a string_view to a local string or a temporary dangles. It is also not guaranteed to be null-terminated, so do not pass data() to C functions expecting C strings.
138

Is it expensive to return a large std::vector from a function by value?

Save to ▾
Show answer
Usually no. Return value optimisation constructs the result directly in the caller's storage, and since C++17 this copy elision is guaranteed when returning a prvalue. For a named local, compilers apply named RVO, and if they cannot, the vector is moved, which only copies three pointers. So return by value is clean and fast. Do not write return std::move(local); because it can block elision.
139

A function returns a string_view and callers sometimes print garbage. What is the likely bug?

Save to ▾
Show answer
The function probably builds or receives a temporary std::string and returns a string_view into it. When the function returns, the string is destroyed and the view dangles. Examples are returning std::string_view(a + b) or a view of a local string. Fix it by returning std::string, or make sure the view refers to data with a longer lifetime, such as a member or static storage.
140

How would you choose between exceptions, error codes and std::expected for error handling?

Save to ▾
Show answer
Exceptions suit rare, truly exceptional failures, keep the happy path clean and work well with RAII, but have unpredictable cost when thrown and are often disabled in embedded or game code. Error codes are explicit and cheap but easy to ignore. C++23 std::expected<T, E> returns either a value or an error, combining explicit handling with clean types. I follow the project convention and use expected for expected failures like parsing.
141

After calling std::move on a string, a teammate prints it and sees an empty value. Is this a bug?

Save to ▾
Show answer
It is a misunderstanding. A moved-from standard library object is in a valid but unspecified state; for std::string it is often empty, but you cannot rely on that. The safe operations are destroying it or assigning a new value. Reading it is not undefined behaviour, but the content is meaningless. Clang-tidy's bugprone-use-after-move check catches this pattern in code review.
142

Write a move constructor and move assignment operator for a class that owns a buffer.

Save to ▾
Show answer
#include <utility> class Buffer { std::size_t size_ = 0; int* data_ = nullptr; public: explicit Buffer(std::size_t n) : size_(n), data_(new int[n]{}) {} ~Buffer() { delete[] data_; } Buffer(Buffer&& other) noexcept : size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {} Buffer& operator=(Buffer&& other) noexcept { if (this != &other) { delete[] data_; size_ = std::exchange(other.size_, 0); data_ = std::exchange(other.data_, nullptr); } return *this; } };
143

Use std::variant and std::visit to handle different message types.

Save to ▾
Show answer
#include <iostream> #include <string> #include <variant> struct Login { std::string user; }; struct Logout { int sessionId; }; using Message = std::variant<Login, Logout>; template <class... Ts> struct Overloaded : Ts... { using Ts::operator()...; }; void handle(const Message& m) { std::visit(Overloaded{ [](const Login& l) { std::cout << "login " << l.user << '\n'; }, [](const Logout& o) { std::cout << "logout " << o.sessionId << '\n'; }}, m); } // Adding a new type without a handler becomes a compile error.
144

Use a C++20 ranges pipeline to get squares of the first three even numbers.

Save to ▾
Show answer
#include <iostream> #include <ranges> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8}; auto result = v | std::views::filter([](int x) { return x % 2 == 0; }) | std::views::transform([](int x) { return x * x; }) | std::views::take(3); for (int x : result) std::cout << x << ' '; // 4 16 36 } // Views are lazy: elements are processed only while iterating.
145

Tell me about a time you convinced your team to adopt a new C++ feature or practice.

Save to ▾
Show answer
Situation: our team avoided smart pointers, and leaks kept reaching QA. Task: get agreement to adopt unique_ptr in new code. Action: I prepared a short benchmark showing no measurable overhead, converted one leaky module as a pilot, and presented before and after defect counts at our tech sync. I also wrote clang-tidy rules to help. Result: the team agreed to make it a coding standard and leak bugs dropped sharply in the next quarter.
146

How do you handle a tight deadline when the C++ code you need to change is complex?

Save to ▾
Show answer
Situation: a client needed a protocol change in two days in code I had not touched. Task: deliver safely. Action: I read the tests first, wrote two new tests for the required behaviour, made the smallest change that passed them, and flagged a risky area to my lead early instead of at the end. I logged a refactoring ticket for later. Result: we shipped on time with no regressions and cleaned up the module the next sprint.
147

What is perfect forwarding?

Save to ▾
Show answer
Perfect forwarding passes arguments through a function template while preserving whether they were lvalues or rvalues. It uses a forwarding reference, T&& where T is deduced, together with std::forward<T>(arg). Example: template <typename... A> void make(A&&... a) { build(std::forward<A>(a)...); }. Without forward, every named parameter is an lvalue and would be copied. make_unique and emplace_back rely on it.
148

What does noexcept mean and why should move constructors be noexcept?

Save to ▾
Show answer
noexcept promises a function will not throw; if it does, std::terminate is called. Containers rely on this: when std::vector reallocates, it moves elements only if the move constructor is noexcept, otherwise it copies them to keep the strong exception guarantee. So a missing noexcept on a move constructor can silently make vector growth much slower. Destructors are noexcept by default.
149

You are asked to modernise a large C++98 codebase to C++17. How would you plan it?

Save to ▾
Show answer
First switch the compiler standard flag and fix build errors, with CI running the full test suite. Then add clang-tidy modernize checks to convert NULL to nullptr, add override and use auto where it helps, applied module by module in small reviewed batches. Next replace raw owning pointers with unique_ptr in new and touched code. I avoid a big-bang rewrite, track progress with metrics and train the team as we go.
150

An asynchronous callback crashes intermittently. It is a lambda that captures local variables by reference. Explain the problem and fix.

Save to ▾
Show answer
The lambda runs later on another thread or event loop, after the function that created it has returned, so the captured references point to destroyed stack variables. Fix it by capturing by value, moving owned data into the lambda with init captures, or capturing a shared_ptr or weak_ptr for objects whose lifetime must be extended or checked. Avoid default [&] for any callback that can outlive the scope.
151

Tell me about a mistake you made in production and what you learned from it.

Save to ▾
Show answer
Situation: I released a change that used string_view in a cache, and a week later we saw corrupted keys. Task: fix it fast and prevent repeats. Action: I rolled back, reproduced the issue with AddressSanitizer, found the views referenced temporary strings, switched to owning std::string keys and wrote a post-mortem. Result: no further incidents, and I added a lifetime checklist and ASan stage to our pipeline that caught two similar bugs later.
152

What is the difference between a process and a thread?

Save to ▾
Show answer
A process is an independent program with its own address space, file handles and resources; processes are isolated and communicate through IPC such as pipes, sockets or shared memory. Threads live inside a process and share its memory and handles, but each has its own stack and registers. Threads are cheaper to create and communicate faster, but shared memory needs synchronisation to avoid races.
153

How do you create a thread in C++ and what is the difference between join and detach?

Save to ▾
Show answer
std::thread t(func, args); starts a new thread running func. join() blocks until the thread finishes, so the caller can safely use its results. detach() lets the thread run independently; you lose the handle and it must not touch objects that may be destroyed. If a joinable std::thread is destroyed without join or detach, std::terminate is called. C++20 std::jthread joins automatically in its destructor.
154

What are race conditions and data races?

Save to ▾
Show answer
A data race occurs when two threads access the same memory at the same time, at least one writes, and there is no synchronisation; in C++ this is undefined behaviour. A race condition is a broader logic bug where the result depends on timing, such as check-then-act on a file or a balance, even if each access is atomic. Mutexes, atomics and careful design of shared state prevent both.
155

Four threads each increment a shared int one million times, but the final total is less than four million. Why?

Save to ▾
Show answer
counter++ is a read-modify-write of three steps, so threads interleave and overwrite each other's updates, which is a data race and undefined behaviour. Fix it with std::atomic<int> and fetch_add, which is fast for a simple counter, or protect the variable with a mutex. Even better for performance, let each thread count in a local variable and add it to the total once at the end.
156

Write a thread-safe counter using std::atomic.

Save to ▾
Show answer
#include <atomic> #include <iostream> #include <thread> #include <vector> int main() { std::atomic<long> hits{0}; std::vector<std::thread> ts; for (int t = 0; t < 4; ++t) ts.emplace_back([&] { for (int i = 0; i < 1000000; ++i) hits.fetch_add(1, std::memory_order_relaxed); }); for (auto& t : ts) t.join(); std::cout << hits.load() << '\n'; // always 4000000 }
157

Describe how you handled an urgent production issue while on call.

Save to ▾
Show answer
Situation: at 2 AM our order service started timing out. Task: restore service quickly and find the cause. Action: I followed the runbook, checked dashboards, saw thread pool saturation after a new release, rolled back within 15 minutes and posted updates in the incident channel. Next day I found a blocking database call inside a worker thread. Result: service was restored fast, and I added a timeout and an alert on queue depth.
158

Tell me about a time you worked with QA to fix a flaky test.

Save to ▾
Show answer
Situation: a multithreaded integration test failed about once in twenty runs and QA kept reopening the ticket. Task: make it reliable without hiding a real bug. Action: I sat with the QA engineer, ran the test in a loop with logging, and saw it used sleep to wait for a worker. I replaced the sleep with a condition variable signal and fixed a small real race we found. Result: 1000 consecutive passes and better trust between dev and QA.
159

Compare std::mutex, lock_guard, unique_lock and scoped_lock.

Save to ▾
Show answer
std::mutex provides lock and unlock, but calling them manually is error-prone. lock_guard is a simple RAII wrapper that locks in the constructor and unlocks in the destructor. unique_lock is more flexible: it can defer locking, unlock early, be moved and is required by condition_variable. scoped_lock, from C++17, locks one or more mutexes at once using a deadlock-avoidance algorithm.
160

What is a deadlock and how do you prevent it?

Save to ▾
Show answer
A deadlock happens when threads wait forever for each other's locks, for example thread A holds m1 and waits for m2 while thread B holds m2 and waits for m1. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always locking in a fixed global order, locking several mutexes together with std::scoped_lock, keeping critical sections small and never calling unknown code while holding a lock.
161

How does std::condition_variable work and what are spurious wakeups?

Save to ▾
Show answer
A condition variable lets a thread sleep until another thread signals that some state changed. The waiter holds a unique_lock and calls cv.wait(lock, predicate), which releases the mutex while sleeping and reacquires it on wake. The notifier changes the state under the mutex and calls notify_one or notify_all. Threads can wake without notification, called spurious wakeups, so always wait with a predicate that rechecks the condition.
162

Explain std::async, std::future and std::promise.

Save to ▾
Show answer
std::async runs a function, possibly on another thread, and returns a std::future that will hold its result or exception; calling get() waits for it. Use std::launch::async to force a new thread. std::promise is the writing end: one thread calls set_value or set_exception, and the paired future receives it. They make simple fork-join tasks easier than manual threads, but are not a full thread pool.
163

What does C++20 std::jthread add over std::thread?

Save to ▾
Show answer
std::jthread joins automatically in its destructor, so forgetting join no longer calls std::terminate. It also supports cooperative cancellation: the thread function can take a std::stop_token, check stop_requested() in its loop, and the owner calls request_stop(), which the destructor also does before joining. std::stop_callback lets you register cleanup actions. This makes long-running worker threads safer to write.
164

A service occasionally freezes and thread dumps show two threads each waiting on a mutex held by the other. How do you fix it?

Save to ▾
Show answer
This is a lock-order deadlock. I would find the two code paths, for example transfer locking account A then B while another locks B then A. The fix is to lock both together with std::scoped_lock(a.m, b.m), or to define a global ordering such as by account ID and always lock lower first. I would also shrink critical sections and add a stress test, and consider TSan or lock hierarchy checks.
165

Design a producer-consumer pipeline where one thread reads log lines and several workers parse them.

Save to ▾
Show answer
I would use a bounded thread-safe queue built with a mutex and two condition variables, one for not empty and one for not full, so a fast reader cannot exhaust memory. The reader pushes lines and workers pop and parse them. For shutdown, the reader pushes a sentinel per worker or sets a closed flag and notifies all. Batching lines per push reduces locking overhead, and results go to a second queue.
166

A program crashes with terminate called without an active exception when a function returns. What is the cause?

Save to ▾
Show answer
A std::thread object that is still joinable was destroyed, often because the function returned early or threw before reaching join. The std::thread destructor calls std::terminate in that case. Fix it by making sure every thread is joined on all paths, using an RAII guard, or switching to std::jthread, which joins automatically. Be careful with detach, since detached threads may access destroyed data.
167

Write a program where two threads print odd and even numbers alternately up to 10.

Save to ▾
Show answer
#include <condition_variable> #include <iostream> #include <mutex> #include <thread> std::mutex m; std::condition_variable cv; int n = 1; const int kMax = 10; void printer(int parity) { std::unique_lock<std::mutex> lk(m); while (true) { cv.wait(lk, [&] { return n > kMax || n % 2 == parity; }); if (n > kMax) break; std::cout << n++ << '\n'; cv.notify_all(); } cv.notify_all(); } int main() { std::thread odd(printer, 1), even(printer, 0); odd.join(); even.join(); }
168

Compute the sum of a large vector in parallel using std::async.

Save to ▾
Show answer
#include <future> #include <numeric> #include <vector> long long parallelSum(const std::vector<int>& v, int parts = 4) { std::vector<std::future<long long>> futs; std::size_t chunk = v.size() / parts; for (int i = 0; i < parts; ++i) { auto b = v.begin() + i * chunk; auto e = (i == parts - 1) ? v.end() : b + chunk; futs.push_back(std::async(std::launch::async, [b, e] { return std::accumulate(b, e, 0LL); })); } long long total = 0; for (auto& f : futs) total += f.get(); return total; } // C++17 alternative: std::reduce(std::execution::par, v.begin(), v.end(), 0LL)
169

Write a deadlock-free money transfer between two bank accounts.

Save to ▾
Show answer
#include <mutex> #include <stdexcept> struct Account { std::mutex m; long long balance = 0; }; void transfer(Account& from, Account& to, long long amount) { if (&from == &to) return; std::scoped_lock lock(from.m, to.m); // locks both without deadlock if (from.balance < amount) throw std::runtime_error("insufficient funds"); from.balance -= amount; to.balance += amount; }
170

What is std::atomic and what do memory orderings mean?

Save to ▾
Show answer
std::atomic<T> makes reads, writes and read-modify-write operations such as fetch_add indivisible and race-free without a mutex. Memory order controls how other memory operations are ordered around it. seq_cst, the default, gives one global order and is easiest to reason about. acquire and release pair up to publish data from one thread to another. relaxed only guarantees atomicity, suitable for simple counters. Weaker orders are faster but harder to get right.
171

You parallelised a loop across eight threads but it became slower than the single-threaded version. What could be wrong?

Save to ▾
Show answer
Likely causes are lock contention when all threads share one mutex, false sharing when per-thread counters sit on the same 64-byte cache line, too little work per task so thread creation dominates, or memory bandwidth limits. I would profile with perf, pad per-thread data with alignas(64) or std::hardware_destructive_interference_size, use thread-local accumulation and a thread pool, and make chunks larger.
172

Many threads read a shared configuration object constantly, but it changes only once an hour. How do you synchronise it efficiently?

Save to ▾
Show answer
A plain mutex would serialise all readers. Option one is std::shared_mutex: readers take shared_lock and run in parallel, the updater takes unique_lock. Option two, often faster, is to keep the config in a std::shared_ptr<const Config> and swap in a new immutable object atomically with std::atomic<std::shared_ptr> in C++20; readers grab a copy of the pointer and never block the writer.
173

A low-latency system needs a queue between two threads with no locks. How would you approach it?

Save to ▾
Show answer
For one producer and one consumer, a single-producer single-consumer ring buffer is the standard answer: a fixed-size array with atomic head and tail indices, using release on publish and acquire on read, and padding so the indices sit on different cache lines. It avoids allocation and syscalls. For multiple producers I would use a proven library rather than writing my own, and verify with stress tests and TSan.
174

Implement a thread-safe blocking queue.

Save to ▾
Show answer
#include <condition_variable> #include <mutex> #include <optional> #include <queue> template <typename T> class BlockingQueue { std::queue<T> q_; std::mutex m_; std::condition_variable cv_; bool closed_ = false; public: void push(T v) { { std::lock_guard<std::mutex> lk(m_); q_.push(std::move(v)); } cv_.notify_one(); } std::optional<T> pop() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [&] { return closed_ || !q_.empty(); }); if (q_.empty()) return std::nullopt; // closed and drained T v = std::move(q_.front()); q_.pop(); return v; } void close() { { std::lock_guard<std::mutex> lk(m_); closed_ = true; } cv_.notify_all(); } };
175

Implement a simple fixed-size thread pool.

Save to ▾
Show answer
#include <condition_variable> #include <functional> #include <mutex> #include <queue> #include <thread> #include <vector> class ThreadPool { std::vector<std::thread> workers_; std::queue<std::function<void()>> tasks_; std::mutex m_; std::condition_variable cv_; bool stop_ = false; public: explicit ThreadPool(std::size_t n) { for (std::size_t i = 0; i < n; ++i) workers_.emplace_back([this] { while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [this] { return stop_ || !tasks_.empty(); }); if (stop_ && tasks_.empty()) return; task = std::move(tasks_.front()); tasks_.pop(); } task(); } }); } void submit(std::function<void()> f) { { std::lock_guard<std::mutex> lk(m_); tasks_.push(std::move(f)); } cv_.notify_one(); } ~ThreadPool() { { std::lock_guard<std::mutex> lk(m_); stop_ = true; } cv_.notify_all(); for (auto& w : workers_) w.join(); } };
176

Tell me about a concurrency bug you investigated and how you solved it.

Save to ▾
Show answer
Situation: a market data service dropped a few updates per day only under heavy load. Task: find the cause without disrupting trading hours. Action: I wrote a stress harness replaying recorded traffic, ran it under ThreadSanitizer and found two threads updating a shared index without synchronisation. I redesigned it to a single-writer model with an SPSC queue. Result: zero dropped updates over a month and latency improved slightly because locks were removed.
177

What is CMake and why is it used for C++ projects?

Save to ▾
Show answer
CMake is a cross-platform build system generator. You describe targets, source files, include paths and dependencies in CMakeLists.txt, and CMake generates Makefiles, Ninja files or Visual Studio projects. Modern CMake is target based, using target_link_libraries and target_include_directories so settings flow to dependents. It integrates with package managers such as vcpkg and Conan and with CTest for running tests.
178

What is the difference between a static library and a dynamic library?

Save to ▾
Show answer
A static library, .a or .lib, is copied into the executable at link time, giving a self-contained binary but larger size and a rebuild for every library update. A dynamic library, .so or .dll, is loaded at run time and shared between processes, saving memory and allowing updates without relinking, but it needs the right version present on the machine and has a small call overhead.
179

Which unit testing frameworks are common in C++?

Save to ▾
Show answer
GoogleTest with GoogleMock is the most widely used; it provides TEST and TEST_F macros, assertions such as EXPECT_EQ and ASSERT_TRUE, fixtures and mocking. Catch2 and doctest are lightweight, header-friendly alternatives with natural syntax. Tests are usually registered with CTest in CMake and run in CI on every merge. Good tests are fast, independent and cover edge cases like empty input and overflow.
180

What are header guards and #pragma once?

Save to ▾
Show answer
Including the same header twice in a translation unit would redefine classes and cause errors. Header guards wrap the file in #ifndef MY_HEADER_H, #define MY_HEADER_H and #endif, so the second inclusion is skipped. #pragma once does the same in one line and is supported by all major compilers, though it is not in the standard. Most modern projects use #pragma once for simplicity.
181

Write a minimal modern CMakeLists.txt for an app with a library and tests.

Save to ▾
Show answer
cmake_minimum_required(VERSION 3.20) project(Inventory LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_library(core src/stock.cpp src/order.cpp) target_include_directories(core PUBLIC include) target_compile_options(core PRIVATE -Wall -Wextra -Wpedantic) add_executable(app src/main.cpp) target_link_libraries(app PRIVATE core) enable_testing() find_package(GTest REQUIRED) add_executable(core_tests tests/stock_test.cpp) target_link_libraries(core_tests PRIVATE core GTest::gtest_main) add_test(NAME core_tests COMMAND core_tests)
182

Measure how long a function takes to run in C++.

Save to ▾
Show answer
#include <chrono> #include <iostream> template <typename F> long long timeMs(F&& f) { auto start = std::chrono::steady_clock::now(); f(); auto end = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); } // usage // auto ms = timeMs([] { heavyWork(); }); // Use steady_clock, not system_clock, because it never jumps backwards.
183

Show the compiler commands to build with strict warnings and sanitizers enabled.

Save to ▾
Show answer
# Strict warnings, treat them as errors g++ -std=c++20 -Wall -Wextra -Wpedantic -Werror -g main.cpp -o app # Address + undefined behaviour sanitizers g++ -std=c++20 -g -O1 -fno-omit-frame-pointer \ -fsanitize=address,undefined main.cpp -o app_asan # Thread sanitizer (separate build) clang++ -std=c++20 -g -O1 -fsanitize=thread main.cpp -o app_tsan # Static analysis clang-tidy main.cpp -- -std=c++20
184

What do compiler optimisation levels like -O0, -O2, -O3 and -Os mean?

Save to ▾
Show answer
-O0 disables optimisation and is best for debugging. -O1 and -O2 enable progressively more optimisations such as inlining, constant propagation and loop optimisations; -O2 is the common release default. -O3 adds aggressive vectorisation and inlining, which may increase code size. -Os optimises for size. Link-time optimisation with -flto optimises across translation units, and -march=native tunes for the current CPU.
185

What is cache locality and why does it matter for performance?

Save to ▾
Show answer
CPUs load memory in cache lines, usually 64 bytes, and access to L1 cache takes a few cycles while main memory takes hundreds. Code that walks memory sequentially, like iterating a std::vector, uses every byte loaded and lets the prefetcher help. Pointer-heavy structures like linked lists jump around memory and cause cache misses. That is why a vector often beats a list even for insert-heavy workloads.
186

Which profiling tools do you use for C++ and what does each show?

Save to ▾
Show answer
On Linux, perf samples the CPU and shows hot functions and call graphs, often visualised as flame graphs. Valgrind callgrind counts instructions precisely but runs slowly, and massif or heaptrack profile memory. gprof is older and needs instrumented builds. Intel VTune and AMD uProf show cache misses and pipeline stalls. On Windows, the Visual Studio profiler covers CPU and memory.
187

What are AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer?

Save to ▾
Show answer
They are compiler instrumentation tools in GCC and Clang. ASan, -fsanitize=address, detects out-of-bounds access, use-after-free, double free and leaks with about 2x slowdown. UBSan, -fsanitize=undefined, catches signed overflow, invalid shifts and null dereferences. TSan, -fsanitize=thread, detects data races but cannot be combined with ASan. Running tests under sanitizers in CI catches bugs long before production.
188

A C++ server crashes with a segmentation fault in production. How do you debug it?

Save to ▾
Show answer
Make sure core dumps are enabled with ulimit -c unlimited or systemd-coredump, and keep debug symbols for release builds. Load the core with gdb binary core, run bt to see the stack trace, then inspect frames and variables. If the stack looks corrupted, reproduce in staging with AddressSanitizer. I would also check logs around the crash time and recent deployments, then add a regression test with the fix.
189

A full build of your C++ project takes 40 minutes. How would you reduce it?

Save to ▾
Show answer
I would measure with Clang -ftime-trace or build tooling to find the slowest files and headers. Then reduce header dependencies using forward declarations and the pimpl idiom, use Ninja for parallel builds, enable ccache or sccache, add precompiled headers for stable heavy headers, and split huge translation units. Unity builds and distributed compilation also help, and CI can cache build outputs.
190

Your application is slow and you are asked to optimise it. Where do you start?

Save to ▾
Show answer
I start by measuring, not guessing. I define a target, such as p99 under 50 ms, create a repeatable benchmark, and profile with perf to find where time actually goes. Then I fix the biggest hotspot first, usually algorithmic complexity, unnecessary copies, allocations or I/O, and re-measure after each change. I keep correctness tests running and stop when the target is met.
191

A binary runs on your laptop but fails on the server with error while loading shared libraries. What is wrong?

Save to ▾
Show answer
The program depends on a shared library that is missing or in a different version on the server, or the loader cannot find it. I would run ldd on the binary to see unresolved libraries, then install the right package, set the rpath at link time, or ship the library alongside. A newer glibc or libstdc++ on the build machine is a common cause; build inside a container matching production, or link statically where allowed.
192

List the gdb commands you would use to debug a crash.

Save to ▾
Show answer
g++ -g -O0 main.cpp -o app # build with debug symbols gdb ./app # or: gdb ./app core (gdb) run arg1 arg2 # start the program (gdb) bt # backtrace after the crash (gdb) frame 2 # select a stack frame (gdb) info locals # show local variables (gdb) print ptr->size # inspect an expression (gdb) break order.cpp:42 # set a breakpoint (gdb) watch total # stop when a variable changes (gdb) next / step / continue # step over, step into, resume
193

Write a GoogleTest unit test for a function, including an edge case.

Save to ▾
Show answer
#include <gtest/gtest.h> #include <stdexcept> #include <vector> double average(const std::vector<int>& v) { if (v.empty()) throw std::invalid_argument("empty"); long long s = 0; for (int x : v) s += x; return static_cast<double>(s) / v.size(); } TEST(AverageTest, ComputesMean) { EXPECT_DOUBLE_EQ(average({2, 4, 6}), 4.0); } TEST(AverageTest, ThrowsOnEmpty) { EXPECT_THROW(average({}), std::invalid_argument); }
194

How do you prioritise when a critical bug and a feature deadline arrive at the same time?

Save to ▾
Show answer
Situation: a customer-facing crash was reported two days before a feature demo. Task: handle both without dropping quality. Action: I informed my lead immediately, estimated both tasks, and we agreed the crash came first because it affected users. I fixed and released it in half a day, then cut one optional part of the feature after agreeing with the product owner. Result: the crash was resolved and the demo went ahead on time.
195

Why should we hire you for this C++ developer role?

Save to ▾
Show answer
Situation: I have prepared specifically for systems-level roles. Task: show I can contribute quickly. Action: I have built projects such as a multithreaded log analyser and a small key-value store in modern C++, used CMake, GoogleTest and sanitizers, and practised data structures and debugging with gdb. Result: I can write safe, measurable, well-tested code from the first sprint, and I learn fast from code reviews and feedback.
196

A low-latency service shows occasional latency spikes of several milliseconds. How would you investigate?

Save to ▾
Show answer
I would first capture latency percentiles and correlate spikes with events. Common causes are heap allocation in the hot path, page faults, lock contention, logging that blocks on I/O, CPU frequency changes and the OS scheduling other work on the same core. Tools include perf, off-CPU flame graphs and tracing. Typical fixes are preallocating memory, pinning threads to isolated cores, async logging and avoiding syscalls in hot paths.
197

You are building a particle simulation with millions of particles. Would you store them as an array of structs or a struct of arrays?

Save to ▾
Show answer
If each update loop touches only a few fields, such as position and velocity, a struct of arrays keeps those fields contiguous, so every cache line is fully used and the compiler can vectorise with SIMD. An array of structs is simpler and better when most fields of one particle are used together. I would benchmark both, and often a hybrid that groups hot fields together works best.
198

Use perf to find the hotspots in a C++ program.

Save to ▾
Show answer
# Build optimised but with symbols and frame pointers g++ -O2 -g -fno-omit-frame-pointer app.cpp -o app perf stat ./app # cycles, instructions, cache misses perf record -g ./app # sample with call graphs perf report # browse hottest functions # Flame graph (with FlameGraph scripts on PATH) perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg perf stat -e cache-misses,branch-misses ./app # specific counters
199

Write a micro-benchmark with Google Benchmark comparing two approaches.

Save to ▾
Show answer
#include <benchmark/benchmark.h> #include <list> #include <numeric> #include <vector> static void BM_VectorSum(benchmark::State& state) { std::vector<int> v(state.range(0), 1); for (auto _ : state) benchmark::DoNotOptimize(std::accumulate(v.begin(), v.end(), 0)); } BENCHMARK(BM_VectorSum)->Range(1 << 10, 1 << 20); static void BM_ListSum(benchmark::State& state) { std::list<int> l(state.range(0), 1); for (auto _ : state) benchmark::DoNotOptimize(std::accumulate(l.begin(), l.end(), 0)); } BENCHMARK(BM_ListSum)->Range(1 << 10, 1 << 20); BENCHMARK_MAIN();
200

Tell me about a performance improvement you delivered and how you measured it.

Save to ▾
Show answer
Situation: our risk calculation batch took 90 minutes and blocked morning reports. Task: bring it under 30 minutes. Action: I profiled with perf and found most time in allocating small objects and a map lookup inside the inner loop. I preallocated buffers, replaced the map with a flat sorted vector and parallelised independent portfolios with a thread pool, validating outputs against the old version. Result: 22 minutes, with identical numbers.

Frequently asked questions

What jobs can I get after learning C++?

C++ opens roles such as C++ developer, software engineer at product companies, embedded software engineer, automotive software developer, game developer, systems programmer and low-latency developer at trading firms. Many companies also use C++ for coding rounds, so strong C++ skills help in general software engineering interviews. Semiconductor, telecom and automotive companies in Bengaluru, Hyderabad, Pune and Noida hire C++ engineers every year.

Who is eligible to learn C++ and do I need prior coding experience?

Anyone who is comfortable with basic logic and mathematics can learn C++. Students of B.Tech, BCA, MCA, B.Sc and diploma programmes take it most often, and working professionals use it to move into systems or product roles. No prior coding experience is strictly required because the course starts from basics, although some familiarity with C or any programming language makes the first two weeks easier.

How long does it take to become job-ready in C++?

With regular practice of two to three hours a day, most learners grasp the fundamentals in six to eight weeks and become interview-ready in three to four months. Becoming job-ready also needs data structures and algorithms practice and two or three solid projects. Advanced areas such as templates, concurrency and low-latency optimisation keep improving with real work experience over the following years.

Is C++ still in demand in 2026?

Yes. C++ remains essential wherever performance and hardware control matter: operating systems, browsers, databases, game engines, AI inference runtimes, automotive and embedded systems, telecom equipment and financial trading. Modern standards such as C++20 and C++23 keep the language current. Demand is especially strong for engineers who combine C++ with multithreading, Linux and system design skills, and competition at the junior level rewards strong fundamentals.

Should I learn C++ or Java or Python for placements?

For coding rounds any of the three works, but C++ is popular because the STL is fast and concise and it is widely used in competitive programming. If you target embedded, gaming, semiconductor or trading roles, C++ is the natural choice. For web backends or enterprise roles Java is common, and Python is preferred for data and AI work. Many engineers learn C++ first for fundamentals and add another language later.

Will I get a certificate and does it help in getting a C++ job?

You receive a course completion certificate that shows you have covered the full syllabus and projects. Recruiters value it as proof of structured learning, but hiring decisions for C++ roles depend mainly on your coding round performance, understanding of memory, OOP and STL, and the quality of your projects. Keep your projects on GitHub with clear READMEs and tests so interviewers can review your actual code.