Skip to content

C++ Interview Questions in Visakhapatnam

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

C++ jobs in Visakhapatnam

Visakhapatnam (Vizag) has a developing IT market with delivery centres, start-ups and IT parks around Rushikonda. Many local candidates also apply to Hyderabad and remote roles, so a mix of service and product styles is common.

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

Solved for VisakhapatnamStart 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 returns a reference to a local variable and the code sometimes works. Explain what is happening.

Save to ▾
Show answer
The local is destroyed when the function returns, so the reference dangles and using it is undefined behaviour. It may seem to work because the old bytes remain on the stack until another call overwrites them. Compilers warn with -Wreturn-local-addr or -Wreturn-stack-address. The fix is to return by value; copy elision and move semantics make returning objects cheap.
02

What is the difference between const int*, int* const and const int* const?

Save to ▾
Show answer
Read the declaration from right to left. const int* p is a pointer to a const int: you cannot modify the value through p, but p can point elsewhere. int* const p is a const pointer to int: the address is fixed but the value can change. const int* const p fixes both the address and the value. These forms are frequent interview traps and appear in function signatures.
03

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

Compute a factorial at compile time.

Save to ▾
Show answer
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; };
05

Is it expensive to return a large std::vector from a function by value?

Save to ▾
Show answer
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

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

What is pointer arithmetic?

Save to ▾
Show answer
Adding an integer to a pointer moves it by that many elements, not bytes, so p + 1 on an int* advances by sizeof(int) bytes. Subtracting two pointers into the same array gives the number of elements between them as ptrdiff_t. Arithmetic is only valid inside an array or one past its end; moving beyond that is undefined behaviour. Contiguous iterators work on the same idea.
08

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

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

Two objects hold shared_ptr references to each other and their memory is never released. Why, and how do you fix it?

Save to ▾
Show answer
This is a reference cycle. Each object keeps the other's reference count above zero, so neither destructor runs even after all outside pointers are gone. Fix it by making one direction non-owning, usually the back pointer, with weak_ptr. For example, a parent holds shared_ptr to its children, while each child holds a weak_ptr to the parent and calls lock() when it needs access.
11

What are AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer?

Save to ▾
Show answer
They are compiler instrumentation tools in GCC and Clang. ASan, -fsanitize=address, detects out-of-bounds access, use-after-free, double free and leaks with about 2x slowdown. UBSan, -fsanitize=undefined, catches signed overflow, invalid shifts and null dereferences. TSan, -fsanitize=thread, detects data races but cannot be combined with ASan. Running tests under sanitizers in CI catches bugs long before production.
12

Write a C++ program that counts how often each word appears in the input.

Save to ▾
Show answer
#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.
13

A production service's memory usage grows steadily over several days. How do you find the cause?

Save to ▾
Show answer
First confirm it is a real leak and not a cache or allocator fragmentation by tracking RSS and allocator statistics. Then reproduce in staging with a heap profiler such as heaptrack or jemalloc profiling and compare snapshots to see which call stacks keep growing. LeakSanitizer catches lost blocks. Common culprits are unbounded maps, shared_ptr cycles and listeners never removed. After the fix, add a long soak test.
14

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

You must find the top 100 most frequent items in a stream of 10 million events. How would you do it?

Save to ▾
Show answer
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.
16

Write a custom hash so a struct can be used as a key in std::unordered_map.

Save to ▾
Show answer
#include <functional> #include <string> #include <unordered_map> struct Point { int x, y; bool operator==(const Point&) const = default; }; struct PointHash { std::size_t operator()(const Point& p) const noexcept { std::size_t h1 = std::hash<int>{}(p.x); std::size_t h2 = std::hash<int>{}(p.y); return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); } }; std::unordered_map<Point, std::string, PointHash> grid;
17

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

Should a Car class inherit from Engine or contain an Engine? Explain your choice.

Save to ▾
Show answer
A car is not an engine, it has an engine, so composition is correct: class Car holds an Engine member or a unique_ptr<Engine>. Inheritance models an is-a relationship and exposes the base interface, which would let callers treat a Car as an Engine. Composition also allows swapping engine types at run time through an interface such as PetrolEngine or ElectricMotor and keeps coupling low.
19

A generic maxOf template gives wrong results when called with two C-style string literals. Why, and how do you fix it?

Save to ▾
Show answer
T is deduced as const char*, so the template compares pointer addresses instead of the characters. The result depends on where the literals are stored. Fix it by adding an overload for const char* that uses std::strcmp, or better, call it with std::string or std::string_view, where operator< compares contents. This shows why generic code must consider what operations mean for each type.
20

Design a producer-consumer pipeline where one thread reads log lines and several workers parse them.

Save to ▾
Show answer
I would use a bounded thread-safe queue built with a mutex and two condition variables, one for not empty and one for not full, so a fast reader cannot exhaust memory. The reader pushes lines and workers pop and parse them. For shutdown, the reader pushes a sentinel per worker or sets a closed flag and notifies all. Batching lines per push reduces locking overhead, and results go to a second queue.
21

Tell me about a time when choosing a better data structure improved performance.

Save to ▾
Show answer
Situation: a pricing job took 40 minutes because it searched a vector of 2 lakh products linearly for every order line. Task: bring it under 5 minutes without changing output. Action: I profiled with perf, confirmed the hot loop, replaced the search with an unordered_map keyed by product ID built once with reserve, and added a regression test. Result: the job finished in about 3 minutes and the team adopted profiling before optimising.
22

Show the copy-and-swap idiom and explain why it gives strong exception safety.

Save to ▾
Show answer
class Buffer { std::size_t n_; int* p_; public: explicit Buffer(std::size_t n) : n_(n), p_(new int[n]{}) {} Buffer(const Buffer& o) : n_(o.n_), p_(new int[o.n_]) { std::copy(o.p_, o.p_ + n_, p_); } ~Buffer() { delete[] p_; } friend void swap(Buffer& a, Buffer& b) noexcept { std::swap(a.n_, b.n_); std::swap(a.p_, b.p_); } Buffer& operator=(Buffer other) noexcept { // copy made before we touch *this swap(*this, other); return *this; } }; // If the copy throws, *this is unchanged; self-assignment is safe too.
23

List the gdb commands you would use to debug a crash.

Save to ▾
Show answer
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
24

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

How do virtual functions work internally?

Save to ▾
Show answer
Most compilers give each polymorphic class a vtable, a static table of function pointers for its virtual functions. Every object stores a hidden vptr pointing to its class's vtable. A call through a base pointer loads the vptr, looks up the slot and jumps to the right override. The cost is one pointer per object, an indirect call and usually no inlining, which matters only in very hot loops.
26

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

When are std::vector iterators invalidated?

Save to ▾
Show answer
Any insertion that causes reallocation, when size exceeds capacity, invalidates all iterators, pointers and references. Insertion without reallocation invalidates those at or after the insertion point. erase invalidates iterators at and after the erased element. clear and resize to a larger size beyond capacity invalidate everything. Holding a pointer to an element and then calling push_back is a classic bug.
28

What is object slicing?

Save to ▾
Show answer
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.
29

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

What are the four pillars of object-oriented programming in C++?

Save to ▾
Show answer
Encapsulation hides data behind a class interface using private members and public methods. Abstraction exposes only what users need, often through abstract base classes. Inheritance lets a derived class reuse and extend a base class. Polymorphism lets one interface behave differently: compile-time through overloading and templates, run-time through virtual functions. Together they help model systems such as bank accounts, shapes or payment methods cleanly.
31

Explain the stages of compiling and running a C++ program.

Save to ▾
Show answer
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.
32

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

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

A full build of your C++ project takes 40 minutes. How would you reduce it?

Save to ▾
Show answer
I would measure with Clang -ftime-trace or build tooling to find the slowest files and headers. Then reduce header dependencies using forward declarations and the pimpl idiom, use Ninja for parallel builds, enable ccache or sccache, add precompiled headers for stable heavy headers, and split huge translation units. Unity builds and distributed compilation also help, and CI can cache build outputs.
35

Compare pass by value, pass by pointer and pass by reference.

Save to ▾
Show answer
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.
36

Reverse a singly linked list using pointers.

Save to ▾
Show answer
struct Node { int val; Node* next; }; Node* reverse(Node* head) { Node* prev = nullptr; while (head) { Node* nxt = head->next; head->next = prev; prev = head; head = nxt; } return prev; } // O(n) time, O(1) extra space.

Few big employers listed in Visakhapatnam?

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

Frequently asked questions

Which companies hire C++ professionals in Visakhapatnam?

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

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

The questions depend more on the company than the city. Visakhapatnam's mix of employers decides the style: Many local candidates also apply to Hyderabad and remote roles, so a mix of service and product styles is common

How do I find C++ jobs in Visakhapatnam?

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