36 practice questions with answers for C++ interviews in Thiruvananthapuram.
C++ jobs in Thiruvananthapuram
Thiruvananthapuram's Technopark is one of India's oldest IT parks, hosting IT-services, product and engineering-services companies. Data and testing teams here often work with global clients in finance, travel and healthcare.
Below are 36 questions that match the mix of service, product and domain employers hiring junior c++ developers in Thiruvananthapuram.
Solved for ThiruvananthapuramStart 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 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.
02
Why are templates usually defined in header files?
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.
03
A teammate complains that a template function produces hundreds of lines of compiler errors when misused. How do you improve this?
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.
04
What are std::optional, std::variant and std::any?
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.
05
Use std::variant and std::visit to handle different message types.
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.
08
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.
09
You must find the top 100 most frequent items in a stream of 10 million events. How would you do it?
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.
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.
11
What is undefined behaviour in C++? Give examples.
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.
12
Sorting a vector of large objects is slow. What can you do?
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.
13
Compare pass by value, pass by pointer and pass by reference.
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.
14
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.
15
What are structured bindings and how do they work with range-based for loops?
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).
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[].
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.
19
What is cache locality and why does it matter for performance?
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.
20
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.
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.
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.
23
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.
24
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.
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.
26
What is the difference between a shallow copy and a deep copy?
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.
27
A teammate added using namespace std; to a shared header file. What problems can this cause?
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.
28
A service occasionally freezes and thread dumps show two threads each waiting on a mutex held by the other. How do you fix it?
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.
29
Tell me about a code review where you pointed out an important issue in a colleague's code.
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.
30
Build times have become very slow because heavy templates are included everywhere. How do you speed them up?
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.
31
How do you prioritise when a critical bug and a feature deadline arrive at the same time?
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.
32
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.
33
Solve two sum: return indices of two numbers that add up to a target.
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 type traits and how does if constexpr use them?
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.
36
What is the difference between push_back and emplace_back?
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.
Which companies hire C++ professionals in Thiruvananthapuram?
Companies with large offices in Thiruvananthapuram include Tata Elxsi. Use their company pages below to practise employer-specific sets.
Are C++ interviews in Thiruvananthapuram different from other cities?
The questions depend more on the company than the city. Thiruvananthapuram's mix of employers decides the style: Data and testing teams here often work with global clients in finance, travel and healthcare
How do I find C++ jobs in Thiruvananthapuram?
Shortlist companies with Thiruvananthapuram offices, keep your CV focused on C++ projects, apply on company career pages and job portals with the Thiruvananthapuram filter, and practise the questions on this page before each interview.