Skip to content

Microsoft C++ Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

About Microsoft hiring for C++ roles

Microsoft builds software, cloud and hardware products including Windows, Microsoft 365, Azure, Dynamics, GitHub, LinkedIn and Xbox. The India Development Center in Hyderabad and Bengaluru is one of its largest engineering hubs outside the US. It hires for software engineers, data scientists, data and applied scientists, and engineers working on Azure data and quality.

For C++ roles, this Microsoft practice set focuses most on Multithreading and Concurrency (7), Modern C++ (C++11 to C++23) (5), Standard Template Library (STL) (4), C++ Basics and Syntax (4). It has 3 easy, 15 medium, 12 hard questions, so you can start easy and work up to the harder ones.

Company type
Product
Headquarters
Redmond, Washington, USA
Main India offices
Hyderabad, Bengaluru, Noida, Gurugram, Pune

Microsoft C++ interview process

  1. Online coding assessment
  2. Technical round 1 (DSA)
  3. Technical round 2 (DSA or design)
  4. Hiring manager round
  5. AA (As Appropriate) round

Typical pattern based on public candidate experiences. Rounds vary by role, team and year.

Solved for MicrosoftStart 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 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.
02

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.
03

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.
04

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.
05

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.
06

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.
07

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.
08

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_; } };
09

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.
10

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.
11

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
12

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.
13

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.
14

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(); }
15

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.
16

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.
17

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.
18

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.
19

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.
20

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.
21

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(); } };
22

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.
23

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.
24

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.
25

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.
26

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.
27

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.
28

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.
29

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(); } };
30

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.

Tips to crack the Microsoft C++ interview

  • Practise DSA on linked lists, trees and graphs, and be ready to write clean, compilable code with edge cases handled.
  • Learn basic Azure data services such as Azure SQL, Synapse and Data Factory if you are applying for data roles.
  • Prepare examples showing a growth mindset, which Microsoft highlights as a core part of its culture.
  • Keep a one-minute story ready for every project on your CV: problem, your part, tools, result.
  • Practise the hard questions on this page aloud; Microsoft interviewers usually ask follow-ups on your first answer.

Frequently asked questions

How many rounds are there in the Microsoft C++ interview?

Candidates usually go through 5 stages: Online coding assessment; Technical round 1 (DSA); Technical round 2 (DSA or design); Hiring manager round; AA (As Appropriate) round. The exact rounds change with the role, team, location and your experience, so confirm the process with the recruiter.

Which topics should I prepare for the Microsoft C++ interview?

This practice set leans on Multithreading and Concurrency (7), Modern C++ (C++11 to C++23) (5), Standard Template Library (STL) (4), C++ Basics and Syntax (4). Revise those first, then practise explaining one or two of your own projects end to end, because most Microsoft interviewers ask you to walk through real work.

Are these the exact questions asked at Microsoft?

No. These are curated practice questions that match the skills and difficulty usually tested in product interviews like Microsoft's. They are not a leaked or verified list of past questions.

Where does Microsoft hire C++ professionals in India?

Microsoft has large teams in Hyderabad, Bengaluru, Noida, Gurugram, Pune. Openings and locations change often, so check the Microsoft careers page and filter by city and experience.

C++ questions for similar companies