40 questions with answers for candidates with 1 year of experience — 17 easy, 23 medium.
What interviewers expect: 1 year experience
With one year of experience, interviewers expect solid fundamentals plus practical exposure: debugging with gdb, writing unit tests, using smart pointers and reading an existing codebase. Questions mix DSA problems with how you fixed real bugs, what you learned from code reviews and how you use STL and modern C++ features in daily work.
This set is weighted towards Templates and Generic Programming (9), C++ Basics and Syntax (8), Performance, Debugging and Build Tools (7), Standard Template Library (STL) (6).
Smart pointers and RAII Debugging and unit tests Modern C++ basics Medium DSA problems
Solved at this levelStart 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
A C++ server crashes with a segmentation fault in production. How do you debug it?
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.
02
When would you use std::set versus std::priority_queue?
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.
03
What are templates in C++? Explain function and class templates.
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.
04
How do you keep your C++ knowledge up to date with new standards?
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.
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.
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.
07
Write a variadic function that sums any number of arguments and one that prints them.
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.
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.
10
What is the difference between new/delete and malloc/free?
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[].
11
Tell me about a time you wrote generic, reusable code that saved effort for your team.
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.
12
Solve two sum: return indices of two numbers that add up to a target.
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.
14
What is the difference between full and partial template specialization?
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.
15
When do you need the typename keyword inside a template?
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.
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
18
A binary runs on your laptop but fails on the server with error while loading shared libraries. What is wrong?
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.
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.
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.
21
Write a function to reverse a string in place without using std::reverse.
#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.
22
A program crashes with terminate called without an active exception when a function returns. What is the cause?
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.
23
Write an efficient function to check whether a number is prime.
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.
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.
25
What is the difference between a declaration and a definition?
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.
26
Your application is slow and you are asked to optimise it. Where do you start?
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.
27
Write a C++ program that counts how often each word appears in the input.
#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.
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.
29
What do compiler optimisation levels like -O0, -O2, -O3 and -Os mean?
-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.
30
Write a generic function template that returns the larger of two values.
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
31
What is the difference between delete and delete[]?
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.
32
Write a minimal modern CMakeLists.txt for an app with a library and tests.
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.
35
Using a custom struct as the key of an unordered_map gives a compile error. Why, and how do you fix it?
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.
36
What is template argument deduction and class template argument deduction?
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.
37
What does the static keyword mean in different contexts?
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.
38
What is the difference between an inline function and a macro?
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.
39
Tell me about a time you found a difficult bug in your C++ code.
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.
40
What is the difference between std::map and std::unordered_map?
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.
Frequently asked questions
What is asked in C++ interviews for 1 year of experience?
With one year of experience, interviewers expect solid fundamentals plus practical exposure: debugging with gdb, writing unit tests, using smart pointers and reading an existing codebase. Questions mix DSA problems with how you fixed real bugs, what you learned from code reviews and how you use STL and modern C++ features in daily work.
How many questions should I practise before a C++ interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 1 year of experience?
Focus first on Smart pointers and RAII, Debugging and unit tests, Modern C++ basics, Medium DSA problems.