Skip to content

C++ Interview Questions in Nagpur

36 practice questions with answers for C++ interviews in Nagpur.

C++ jobs in Nagpur

Nagpur's MIHAN SEZ hosts IT-services and BFSI delivery centres, giving central India a steady market for data and QA roles. Interviews are usually service-company style, with aptitude, technical and HR rounds.

Below are 36 questions that match the mix of service, product and domain employers hiring junior c++ developers in Nagpur.

Solved for NagpurStart 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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
15

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

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

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); }
18

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

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

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]; } };
21

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

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);
23

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

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

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

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

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

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

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

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

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

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

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
34

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

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

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.

Few big employers listed in Nagpur?

Many Nagpur candidates also apply to teams in Pune and to remote or hybrid roles. Practise the Pune set as well.

Frequently asked questions

Which companies hire C++ professionals in Nagpur?

Companies with large offices in Nagpur include many IT services and product firms. Use their company pages below to practise employer-specific sets.

Are C++ interviews in Nagpur different from other cities?

The questions depend more on the company than the city. Nagpur's mix of employers decides the style: Interviews are usually service-company style, with aptitude, technical and HR rounds

How do I find C++ jobs in Nagpur?

Shortlist companies with Nagpur offices, keep your CV focused on C++ projects, apply on company career pages and job portals with the Nagpur filter, and practise the questions on this page before each interview.