36 practice questions with answers for C++ interviews in Coimbatore.
C++ jobs in Coimbatore
Coimbatore has a growing IT-services and engineering-services market around TIDEL Park and its SEZs, supported by a large pool of engineering graduates. Many roles are with delivery centres of bigger IT firms.
Below are 36 questions that match the mix of service, product and domain employers hiring junior c++ developers in Coimbatore.
Solved for CoimbatoreStart 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
Your program crashes with the message double free or corruption. What could cause it?
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.
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.
03
Show the compiler commands to build with strict warnings and sanitizers enabled.
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.
06
What is CMake and why is it used for C++ projects?
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.
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.
08
Explain the rule of three, rule of five and rule of zero.
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.
#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.
10
Memory leaks appear when derived objects stored as Base* are deleted. What is wrong and how do you fix it?
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.
11
What is a pointer and how is it different from a reference?
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.
12
Describe a time you improved code quality by changing how memory was managed.
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.
13
Compute the sum of a large vector in parallel using std::async.
#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)
14
Explain the stages of compiling and running a C++ program.
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
Write a lookup function that uses std::optional instead of returning -1 or a null pointer.
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.
17
Compare std::mutex, lock_guard, unique_lock and scoped_lock.
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.
18
A program that prints a million lines with std::endl is very slow. Why, and how do you fix it?
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.
19
What are the main components of the Standard Template Library?
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.
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.
21
The linker reports undefined reference to a function that is declared in a header. What could be wrong?
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.
22
Code that erases elements from a vector inside a range-based for loop crashes. Why, and what is the correct way?
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.
23
What is std::string_view and what are its pitfalls?
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.
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.
25
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.
26
Describe a time you had to learn a new library or API quickly.
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.
27
Code that takes bool& from a std::vector<bool> fails to compile. Why?
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.
28
Tell me about a time you convinced your team to adopt a new C++ feature or practice.
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.
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; };
30
Implement a generic Stack class template backed by std::vector.
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.
32
Why should you prefer make_unique and make_shared over calling new directly?
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.
33
Explain move semantics and what std::move actually does.
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.
34
What does C++20 std::jthread add over std::thread?
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.
35
What is the difference between overloading and overriding, and what do override and final do?
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.
36
Write a C++20 concept and use it to constrain a function.
Which companies hire C++ professionals in Coimbatore?
Companies with large offices in Coimbatore include many IT services and product firms. Use their company pages below to practise employer-specific sets.
Are C++ interviews in Coimbatore different from other cities?
The questions depend more on the company than the city. Coimbatore's mix of employers decides the style: Many roles are with delivery centres of bigger IT firms
How do I find C++ jobs in Coimbatore?
Shortlist companies with Coimbatore offices, keep your CV focused on C++ projects, apply on company career pages and job portals with the Coimbatore filter, and practise the questions on this page before each interview.