Information Technology
C++ Interview Questions & Answers
Prepare for your C++ interview with 174+ curated questions and answers, organised into 16 topics from beginner to advanced. Each topic also has tutorials and MCQ practice.
Casting & Conversions
All 12 questions- What are the four C++ named casts? Beginner
C++ provides static_cast (compile-time, related-type conversions), dynamic_cast (safe downcasting in polymorphic hierarchies, checked at runtime), const_cast (add/remove const/vola…
- What is static_cast used for? Beginner
static_cast performs well-defined conversions known at compile time: numeric conversions (int to double), converting between related pointer types in a hierarchy (up or down withou…
- What is dynamic_cast and when do you use it? Intermediate
dynamic_cast safely converts pointers/references within a polymorphic class hierarchy (the base must have a virtual function), checking at run time using RTTI. On a pointer, it ret…
- What is reinterpret_cast and why is it dangerous? Intermediate
reinterpret_cast reinterprets the bit pattern of one type as another (e.g., pointer to integer, or between unrelated pointer types). It performs no conversion of value, only a comp…
A C-style cast (int)x tries static_cast, then const_cast, then reinterpret_cast (and combinations) in sequence, so it can silently perform a dangerous reinterpret or strip const wi…
Compilation & Linking
All 11 questionsBuilding involves: preprocessing (handling #include/#define to produce a translation unit), compilation (translating each translation unit to an object file, checking syntax and ty…
- What is a translation unit? Beginner
A translation unit is a single source file after preprocessing—the .cpp file with all its #included headers textually expanded. The compiler processes one translation unit at a tim…
A declaration introduces a name and its type (promising it exists somewhere); a definition also provides the implementation/storage. You can declare something many times but define…
- What is the One Definition Rule (ODR)? Intermediate
The ODR states that every entity (variable, function, class, template) must have exactly one definition across the whole program (with specific exceptions: inline functions/variabl…
External linkage means a name is visible across translation units (can be referenced from other files)—the default for non-const globals and functions. Internal linkage confines a…
Concepts & Constraints
All 10 questions- What are C++20 concepts? Beginner
Concepts are named, compile-time predicates that constrain template parameters—specifying the requirements a type must satisfy (e.g., must be sortable, must support +). They make t…
Without concepts, using a template with an unsupported type produces long, cryptic errors deep inside the template's body. Concepts check requirements at the call site and report a…
You can constrain templates via: a concept name in place of typename (template ), a requires clause (template requires C ), a trailing requires clause after the function signature,…
- What is a requires expression? Intermediate
A requires expression (requires(T a){ ... }) is a compile-time check that yields true if the enclosed operations/requirements are valid for the given types. It's used to define con…
SFINAE with std::enable_if constrains templates by making invalid substitutions silently remove overloads—powerful but cryptic and hard to read/maintain. Concepts express the same…
Const Correctness
All 12 questions- What does const mean in C++? Beginner
const declares that something won't be modified after initialization. Applied to a variable, it makes it read-only; to a function parameter, it promises not to change the argument;…
- What is a const member function? Beginner
A const member function (declared with const after the parameter list) promises not to modify the object's observable state and can be called on const objects. Inside it, member va…
'Pointer to const' (const int* p) means the pointed-to value can't be changed through p, but p can point elsewhere. 'Const pointer' (int* const p) means p can't be repointed, but t…
- What is the mutable keyword? Intermediate
mutable allows a member variable to be modified even inside a const member function (or of a const object). It's used for members that don't affect the object's logical/observable…
Physical (bitwise) constness means no bits of the object change. Logical constness means the object's observable/meaningful state doesn't change, even if some internal bits (like a…
Constexpr & Compile-Time
All 11 questions- What does constexpr mean? Beginner
constexpr indicates that a value or function can be evaluated at compile time. A constexpr variable is a compile-time constant; a constexpr function can be evaluated at compile tim…
const means the value won't change after initialization but it may be initialized at run time. constexpr means the value is a compile-time constant and must be initializable at com…
A constexpr function must be able to produce a compile-time constant when given constant arguments: historically its body was limited (single return in C++11), but C++14+ allows lo…
- What is consteval (C++20)? Intermediate
consteval declares an 'immediate function' that must be evaluated at compile time—every call must produce a constant, otherwise it's a compile error. Unlike constexpr (which may ru…
- What is constinit (C++20)? Intermediate
constinit guarantees that a variable with static/thread storage duration is initialized at compile time (constant initialization), preventing the 'static initialization order fiasc…
Coroutines
All 10 questions- What is a coroutine in C++20? Beginner
A coroutine is a function that can suspend its execution and resume later, preserving its local state across suspensions. A function becomes a coroutine if its body uses co_await,…
co_await suspends the coroutine until an awaited operation is ready, then resumes. co_yield suspends and produces a value to the caller (used for generators), resuming on the next…
A regular function runs to completion in one invocation using a single stack frame that's destroyed on return. A coroutine can suspend and resume, so its state (locals, execution p…
A generator is a function producing a sequence of values lazily, one at a time, on demand. With coroutines, co_yield suspends and hands back a value each time the consumer asks for…
A coroutine's return type must provide a promise_type controlling its behavior (initial/final suspend, how co_yield/co_return/exceptions are handled, and how the return object is b…
Enums & Enum Classes
All 10 questionsAn enum defines a type with a set of named integer constants (enumerators), improving readability over magic numbers. Unscoped enums (enum Color { Red, Green };) put the names in t…
An enum class (scoped enumeration, C++11) scopes its enumerators to the enum's name (Color::Red) and does not implicitly convert to int, preventing accidental mixing with numbers o…
- How do you specify the underlying type of an enum? Intermediate
You can specify the integer type backing an enum with a colon: enum class Flag : std::uint8_t { ... }. This controls the size and range, useful for memory layout, serialization, an…
Because enum class doesn't convert implicitly, you convert explicitly with static_cast: static_cast (e) to get the value, and static_cast (i) to build an enum from an integer. C++2…
You can assign explicit integer values to enumerators; unassigned ones continue incrementing from the previous value. This is used to match external codes, create bit flags (powers…
I/O Streams
All 10 questions- What are C++ I/O streams? Beginner
C++ streams are a type-safe, extensible I/O abstraction in : std::cin (input), std::cout (output), std::cerr (unbuffered error), and std::clog (buffered log). They use operator > (…
std::cout is the standard output stream (buffered). std::cerr is the standard error stream, unbuffered so messages appear immediately (good for errors). std::clog is also for loggi…
std::ifstream opens a file for reading and std::ofstream for writing; std::fstream does both. They're RAII—opening in the constructor and closing in the destructor—and use the same…
operator>> extracts formatted, whitespace-delimited tokens (skipping leading whitespace and stopping at the next whitespace), good for reading numbers/words. std::getline reads an…
Streams have state flags: good(), eof() (end of file reached), fail() (format/logic error), and bad() (serious error). A stream is convertible to bool (true if not failed), so you…
Lambda Expressions
All 12 questions- What is a lambda expression in C++? Beginner
A lambda expression is an anonymous function object defined inline, introduced in C++11. It has the form [captures](params){ body } and can be stored, passed to algorithms, or call…
The capture list [...] specifies which surrounding variables the lambda can use and how. [x] captures x by value (a copy), [&x] by reference, [=] captures all used variables by val…
Capturing by value copies the variable into the closure at creation time, so later changes to the original don't affect the lambda and the copy is safe to use after the original's…
- What is a mutable lambda? Intermediate
By default, a lambda's operator() is const, so by-value captured variables can't be modified inside the body. Marking the lambda mutable removes the const, allowing modification of…
- How do you specify a lambda's return type? Intermediate
Usually the return type is deduced from the return statements. When deduction is ambiguous or you want an explicit type, use a trailing return type: [](int x) -> double { ... }. Ex…
Memory Management
All 12 questionsThe stack is a region of memory for automatic (local) variables, managed by the compiler with LIFO allocation and fast, deterministic lifetime tied to scope. The heap (free store)…
- What do new and delete do? Beginner
new allocates memory on the heap and constructs an object, returning a pointer; delete calls the destructor and frees the memory. For arrays use new[] and delete[]. Every new must…
- What is a memory leak? Beginner
A memory leak occurs when heap memory is allocated but never freed, so it remains reserved for the program's lifetime, gradually exhausting available memory. Leaks happen when a de…
- What is a dangling pointer and how does it arise? Intermediate
A dangling pointer points to memory that has been freed or gone out of scope, so dereferencing it is undefined behavior. It arises from using a pointer after delete, returning the…
malloc/free are C library functions that only allocate/free raw memory and don't call constructors or destructors; new/delete are C++ operators that also construct and destruct obj…
Namespaces
All 11 questions- What is a namespace and why use one? Beginner
A namespace is a named scope that groups related declarations (functions, classes, variables) to prevent name collisions between different libraries or modules. Qualifying names wi…
using namespace std; brings all names from std into the current scope so you can omit the std:: prefix. It's discouraged, especially in headers, because it pollutes the global/name…
A using-declaration (using std::vector;) brings a single name into scope. A using-directive (using namespace std;) brings all names from a namespace into scope. Using-declarations…
- What is an anonymous (unnamed) namespace? Intermediate
An unnamed namespace gives its contents internal linkage—they're visible only within the current translation unit, like static at file scope but working for types too. It's the mod…
ADL (Koenig lookup) means that when calling an unqualified function, the compiler also searches the namespaces of the argument types for matching functions. This lets operators and…
Preprocessor & Macros
All 10 questions- What is the C++ preprocessor? Beginner
The preprocessor is a text-processing step that runs before compilation, handling directives beginning with # : #include (textual inclusion of headers), #define (macros), and condi…
#include searches the system/standard include directories (used for standard and library headers). #include "name" searches the current directory first (then the system paths), use…
An include guard prevents a header's contents from being included more than once in a translation unit, which would cause redefinition errors. It uses #ifndef/#define/#endif around…
Function-like macros do blind text substitution with no type checking, no scope, and pitfalls like multiple argument evaluation and operator-precedence bugs. Modern C++ replaces th…
#if/#ifdef/#ifndef/#else/#endif include or exclude code at compile time based on macros—used for platform-specific code, feature toggles, debug/release differences, and include gua…
Ranges & Views
All 10 questions- What are C++20 ranges? Beginner
Ranges (C++20) are an abstraction over 'something you can iterate'—anything with a begin and end—paired with algorithms that operate on whole ranges instead of iterator pairs. The…
A view is a lightweight, non-owning, lazily-evaluated range that adapts another range without copying its elements. Views (like std::views::filter, std::views::transform) compute e…
- What does the pipe operator | do with ranges? Intermediate
The | operator composes range adaptors into a pipeline, feeding the output of one view into the next, read left to right. It makes transformations readable, like Unix pipes: range…
- What are some commonly used range adaptors? Intermediate
Common adaptors include views::filter (keep elements matching a predicate), views::transform (apply a function), views::take/drop (first/skip n), views::reverse, views::join (flatt…
Views compute elements only when iterated and don't store results, so composing many views avoids intermediate allocations and can short-circuit (e.g., with take). But re-iterating…
Strings & string_view
All 11 questionsstd::string is a class that owns and manages a dynamically-sized sequence of characters, handling memory automatically, growth, and many operations (concatenation, search, substr).…
std::string_view (C++17) is a non-owning, read-only view over a contiguous sequence of characters (a pointer plus length). It avoids copying when you only need to read a string, an…
- What are the dangers of std::string_view? Intermediate
Because string_view doesn't own its data, it dangles if the underlying string is destroyed or modified (e.g., a view of a temporary, or of a std::string that reallocates). You must…
- How does std::string manage memory and what is SSO? Intermediate
std::string allocates a heap buffer for its characters and grows it as needed (amortized, like vector). Most implementations use Small String Optimization (SSO): short strings are…
Use std::to_string(n) to convert numbers to strings, and std::stoi/std::stol/std::stod etc. to parse strings to numbers. C++17 adds std::from_chars/std::to_chars for fast, locale-i…
Type Deduction & auto
All 12 questions- What is the auto keyword? Beginner
auto lets the compiler deduce a variable's type from its initializer, reducing verbosity and coupling to exact types. auto x = expr; gives x the type of expr (with top-level const…
auto deduces a value type (a copy, dropping references/top-level const). auto& deduces a (mutable) reference to the source, avoiding a copy and allowing modification. const auto& d…
- How does template argument deduction work? Intermediate
When you call a template function, the compiler deduces the template parameters from the argument types, following rules similar to auto. For a parameter T (by value), references a…
- What is decltype and how does it differ from auto? Intermediate
decltype(expr) yields the declared type of an expression without evaluating it, preserving references and const exactly (unlike auto, which strips them for value deduction). It's u…
decltype(auto) (C++14) deduces a type using decltype rules rather than auto rules, so it preserves references and const. It's used mainly for return types of forwarding/wrapper fun…
Undefined Behavior
All 10 questionsUndefined behavior is program behavior the C++ standard places no requirements on—anything can happen: a crash, wrong results, or seemingly working code that breaks later or under…
- What is the difference between undefined, unspecified, and implementation-defined behavior? Beginner
Undefined behavior has no constraints—anything may happen (must be avoided). Unspecified behavior has several allowed outcomes and the implementation need not document which (e.g.,…
- What are common causes of undefined behavior? Intermediate
Common UB: out-of-bounds array/container access, dereferencing null or dangling pointers, use-after-free/double-free, reading uninitialized variables, signed integer overflow, data…
Unsigned overflow is defined to wrap modulo 2^n. Signed overflow is undefined because the standard doesn't fix a representation-independent result, and leaving it UB lets compilers…
Strict aliasing says you generally may not access an object through a pointer/reference of an incompatible type (with some exceptions like char/std::byte). Violating it—e.g., reint…