C++ MCQ
Test your C++ knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.
How This Practice Test Works
Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
1
What is the correct file extension for a C++ source file?
Correct Answer
.cpp
Explanation
C++ source files commonly use the .cpp extension. .cc, .cxx, and .C are also accepted by many compilers.
2
Which header file must be included to use cout in C++?
Correct Answer
<iostream>
Explanation
#include <iostream> provides std::cout, std::cin, and std::cerr for I/O operations.
3
What does cout stand for?
Correct Answer
Character Output
Explanation
cout stands for "character output" and is used with the << insertion operator to write to standard output.
4
What is the correct syntax to define a variable of type integer?
Correct Answer
int x = 5;
Explanation
C++ uses primitive type keywords: int, double, char, bool, etc. followed by the variable name.
5
What is the entry point of a C++ program?
Correct Answer
main()
Explanation
Every C++ program starts execution from the main() function. It returns int (typically 0 on success).
6
What does the :: operator represent in C++?
Correct Answer
Scope resolution operator
Explanation
:: is the scope resolution operator. std::cout uses it to access cout from the std namespace.
7
What is a pointer in C++?
Correct Answer
A variable that stores a memory address
Explanation
A pointer stores the memory address of another variable. Declared as int* ptr; and dereferenced with *ptr.
8
What is the difference between & and * when declaring variables?
Correct Answer
& declares a reference; * declares a pointer
Explanation
int& ref = x declares a reference (alias). int* ptr = &x declares a pointer holding the address of x.
9
What is a reference in C++?
Correct Answer
An alias for an existing variable that must be initialized at declaration
Explanation
A reference is an alias; it must be initialized when declared and cannot be reseated to refer to a different variable.
10
Which keyword allocates memory on the heap in C++?
Correct Answer
new
Explanation
new allocates memory and calls the constructor. The memory must be freed with delete (or delete[] for arrays).
11
What is function overloading in C++?
Correct Answer
Defining multiple functions with the same name but different parameter lists
Explanation
C++ allows multiple functions with the same name as long as they differ in parameter types or count.
12
What keyword is used to define a class in C++?
Correct Answer
class
Explanation
The class keyword defines a class. The main difference from struct is that class members are private by default.
13
What is the default access specifier for members of a class?
Correct Answer
private
Explanation
Class members are private by default. Struct members are public by default.
14
What is a destructor?
Correct Answer
A function called automatically when an object goes out of scope to release resources
Explanation
Destructors (~ClassName()) are called automatically when an object is destroyed, used to release heap memory, file handles, etc.
15
What does the virtual keyword do?
Correct Answer
Enables runtime polymorphism by allowing derived classes to override the function
Explanation
virtual methods are dispatched at runtime through a vtable, enabling polymorphism when calling through a base class pointer or reference.
16
What is a pure virtual function?
Correct Answer
A virtual function with = 0; making the class abstract
Explanation
virtual void draw() = 0; declares a pure virtual function. Classes with pure virtual functions are abstract and cannot be instantiated.
17
What does the const keyword on a member function mean?
Correct Answer
The function does not modify any member variables of the object
Explanation
void show() const; guarantees the function won't modify the object's state. It can be called on const objects.
18
What is a template in C++?
Correct Answer
A mechanism for writing generic code that works with any type
Explanation
Templates allow writing type-generic functions and classes. template<typename T> T max(T a, T b) works for any comparable type T.
19
What is the STL?
Correct Answer
Standard Template Library
Explanation
The Standard Template Library provides generic containers (vector, map, set), algorithms (sort, find), and iterators.
20
What is a vector in C++?
Correct Answer
A dynamic array that resizes automatically
Explanation
std::vector<T> is a dynamic array with O(1) random access and amortized O(1) push_back.
21
What does #include do?
Correct Answer
Inserts the contents of a header file at compile time
Explanation
#include is a preprocessor directive that copies the contents of the specified file into the source file before compilation.
22
What is the difference between stack and heap memory?
Correct Answer
Stack is automatically managed (local variables); heap requires manual management (new/delete)
Explanation
Stack memory is allocated/freed automatically with function calls. Heap memory persists until explicitly freed with delete, enabling dynamic lifetimes.
23
What is a namespace?
Correct Answer
A region that provides scope to identifiers, preventing name collisions
Explanation
namespace myLib { ... } groups related names. using namespace std; brings all std names into scope.
24
What does endl do?
Correct Answer
Outputs a newline and flushes the output buffer
Explanation
endl inserts '\n' and calls flush(). Use '\n' for just a newline without flushing, which is faster in tight loops.
25
What is the size of a bool in C++?
Correct Answer
Implementation-defined, at least 1 byte
Explanation
The C++ standard says bool is at least 1 byte (to be addressable). Its exact size is implementation-defined but typically 1 byte.
26
What is operator overloading?
Correct Answer
Defining custom behavior for operators when applied to user-defined types
Explanation
Operator overloading lets you define + for your class: Vector operator+(const Vector& other) const.
27
What is a copy constructor?
Correct Answer
A constructor that initializes an object as a copy of another object of the same type
Explanation
MyClass(const MyClass& other) is called when passing by value or initializing from an existing object. If not defined, the compiler generates a shallow copy.
28
What is the this pointer?
Correct Answer
A pointer to the current object instance
Explanation
this is an implicit pointer available in non-static member functions, pointing to the object on which the method is called.
29
What is inheritance in C++?
Correct Answer
A mechanism where a derived class acquires members from a base class
Explanation
class Dog : public Animal means Dog inherits Animal's public and protected members.
30
What does the delete operator do?
Correct Answer
Frees heap memory allocated with new and calls the destructor
Explanation
delete ptr; calls the destructor and frees the memory. delete[] arr; must be used for arrays allocated with new[].
31
What is the difference between struct and class in C++?
Correct Answer
struct members are public by default; class members are private by default
Explanation
struct and class are nearly identical in C++. The only difference is default access: struct defaults to public, class to private.
32
What is a static member in C++?
Correct Answer
A member shared by all instances of a class, existing independently of any object
Explanation
static data members are shared across all objects. Static member functions can be called without an instance and cannot access non-static members.
33
What does the inline keyword suggest for a function?
Correct Answer
The compiler should substitute the function body at call sites to avoid call overhead
Explanation
inline is a suggestion (not a command) to the compiler. Modern compilers often inline regardless of the keyword based on optimization flags.
34
What is the range-based for loop syntax in C++11?
Correct Answer
for (auto x : collection)
Explanation
The range-based for (for (auto x : v)) iterates over all elements, using begin() and end() iterators internally.
35
What is a nullptr?
Correct Answer
A type-safe null pointer constant introduced in C++11
Explanation
nullptr is the C++11 null pointer constant of type std::nullptr_t. It's safer than NULL or 0 because it doesn't convert to int.
36
What does auto mean when declaring a variable in C++11?
Correct Answer
The compiler deduces the type from the initializer
Explanation
auto x = 3.14; deduces x as double. auto reduces verbosity, especially with iterators and complex template types.
37
What is the purpose of the const qualifier on a variable?
Correct Answer
The variable's value cannot be changed after initialization
Explanation
const int MAX = 10; prevents MAX from being modified. The compiler enforces this at compile time.
38
What is function call by reference?
Correct Answer
Passing the memory address so the function can modify the original
Explanation
void increment(int& x) { x++; } modifies the original variable. No copy is made; the parameter is an alias for the argument.
39
What is a string in C++?
Correct Answer
std::string is the standard class for strings with safe operations; char arrays are the C-style alternative
Explanation
std::string from <string> provides safe string handling. C-style char arrays (char[]) are lower-level and require manual null-termination.
40
What is a memory leak?
Correct Answer
Heap memory that is allocated but never freed, causing the program to consume increasing memory
Explanation
Memory leaks occur when new is called without a matching delete. Over time, leaked memory accumulates until the system runs out of resources.
1
What is RAII (Resource Acquisition Is Initialization)?
Correct Answer
A C++ idiom where resources are acquired in constructors and released in destructors, tying resource lifetime to object lifetime
Explanation
RAII ensures resources (memory, files, locks) are released when an object goes out of scope. Smart pointers and std::lock_guard implement RAII.
2
What is a smart pointer?
Correct Answer
An object that acts like a pointer but manages the lifetime of the pointed-to object automatically
Explanation
Smart pointers (unique_ptr, shared_ptr, weak_ptr) use RAII to automatically delete objects when no longer needed, preventing memory leaks.
3
What is the difference between unique_ptr and shared_ptr?
Correct Answer
unique_ptr enforces exclusive ownership (non-copyable); shared_ptr allows shared ownership via reference counting
Explanation
unique_ptr is zero-overhead exclusive ownership. shared_ptr maintains a reference count and deletes the object when the count reaches 0.
4
What is a move constructor?
Correct Answer
A constructor that transfers ownership of resources from a temporary (rvalue) object without copying
Explanation
Move constructors (MyClass(MyClass&&)) steal resources from rvalues, enabling efficient transfers without expensive copies (e.g., std::vector reallocation).
5
What are lvalue and rvalue in C++?
Correct Answer
lvalue: has a persistent address/identity; rvalue: a temporary without a persistent address
Explanation
lvalues persist beyond an expression (you can take their address). rvalues are temporaries. Move semantics and && references exploit rvalues.
6
What is std::move?
Correct Answer
Casts an lvalue to an rvalue reference, enabling move semantics
Explanation
std::move(x) is a cast to rvalue reference. It signals "I no longer need x," allowing move constructors/assignment to transfer resources efficiently.
7
What is template specialization?
Correct Answer
Providing optimized or different behavior for a specific type in a template
Explanation
template<> void swap<std::string>(std::string& a, std::string& b) provides a custom implementation for std::string while the generic template handles all other types.
8
What is the vtable?
Correct Answer
A per-class table of function pointers used to resolve virtual function calls at runtime
Explanation
Each class with virtual functions has a vtable. Each object has a vptr pointing to its class's vtable. Virtual calls are resolved via indirection through the vtable.
9
What is the Rule of Five in C++11?
Correct Answer
If a class needs any of destructor, copy constructor, copy assignment, move constructor, or move assignment, it likely needs all five
Explanation
The Rule of Five extends the Rule of Three (destructor, copy ctor, copy assignment) with move constructor and move assignment, for proper resource management.
10
What is SFINAE?
Correct Answer
Substitution Failure Is Not An Error: invalid template substitutions are silently discarded rather than causing compile errors
Explanation
SFINAE enables conditional template instantiation. If template substitution fails (e.g., a type lacks a method), that overload is removed from consideration without a compile error.
11
What does std::enable_if do?
Correct Answer
Conditionally enables or disables a template based on a boolean condition using SFINAE
Explanation
std::enable_if<std::is_integral<T>::value, T>::type restricts a template to integral types, removing non-matching specializations from overload resolution.
12
What is perfect forwarding?
Correct Answer
Forwarding arguments to another function preserving lvalue/rvalue category via std::forward
Explanation
template<typename T> void wrapper(T&& arg) { target(std::forward<T>(arg)); } forwards lvalues as lvalues and rvalues as rvalues, avoiding unnecessary copies.
13
What is a lambda expression in C++11?
Correct Answer
An anonymous function object defined inline, optionally capturing surrounding variables
Explanation
[&](int x) { return x + y; } is a lambda capturing y by reference. [=] captures by value. The compiler generates a closure class.
14
What is constexpr?
Correct Answer
A specifier enabling functions and variables to be evaluated at compile time
Explanation
constexpr int factorial(int n) { ... } may be evaluated at compile time when called with a constant argument, producing zero runtime overhead.
15
What is std::optional?
Correct Answer
A wrapper that may or may not contain a value, representing an optional result without a null pointer
Explanation
std::optional<T> (C++17) holds either a T or nothing. Check with .has_value() and access with .value() or operator*.
16
What is structured bindings (C++17)?
Correct Answer
A syntax to unpack struct, array, or tuple members into named local variables: auto [a, b] = pair
Explanation
auto [x, y] = point; binds the members of point. Works with arrays, std::pair, std::tuple, and aggregates.
17
What is a variadic template?
Correct Answer
A template accepting an arbitrary number of type parameters
Explanation
template<typename... Args> void log(Args&&... args) accepts any number of type arguments. The ... pack expansion applies the operation to each argument.
18
What is the purpose of weak_ptr?
Correct Answer
A non-owning reference to a shared_ptr-managed object that doesn't prevent deletion, breaking reference cycles
Explanation
weak_ptr does not increase the reference count. Convert to shared_ptr with lock() to access the object. Used to break shared_ptr reference cycles.
19
What is undefined behavior in C++?
Correct Answer
Code whose behavior the C++ standard does not define — the compiler may do anything, including crash, produce wrong results, or appear to work
Explanation
UB examples: signed integer overflow, null pointer dereference, out-of-bounds access. UB allows compilers to make optimizing assumptions that can break seemingly correct code.
20
What does the noexcept specifier do?
Correct Answer
Prevents exceptions from being thrown; any exception causes std::terminate
Explanation
void f() noexcept; guarantees no exception escapes. If one does, std::terminate is called. noexcept enables compiler optimizations, especially for move operations.
21
What is copy elision?
Correct Answer
The compiler's ability to eliminate unnecessary copy or move operations
Explanation
Named Return Value Optimization (NRVO) and Return Value Optimization (RVO) are forms of copy elision guaranteed by C++17, constructing the object directly in the caller's storage.
22
What is the std::string_view (C++17)?
Correct Answer
A non-owning read-only reference to a character sequence, avoiding copies when only read access is needed
Explanation
string_view is a lightweight (pointer + length) view into an existing string. It avoids allocation when passing substrings or literals to functions.
23
What is an initializer list (std::initializer_list)?
Correct Answer
A lightweight proxy for a braced-init-list enabling containers to be constructed with { ... } syntax
Explanation
std::initializer_list<int> allows vector<int> v = {1,2,3}. A constructor taking initializer_list is preferred when braced initialization is used.
24
What does decltype do?
Correct Answer
Deduces the declared type of an expression without evaluating it
Explanation
decltype(expr) gives the type of the expression. Used in trailing return types: auto add(T a, U b) -> decltype(a + b).
25
What is the difference between const int* and int* const?
Correct Answer
const int* is a pointer to const int (value can't change); int* const is a const pointer to int (address can't change)
Explanation
Read right-to-left: int* const p — p is a const pointer to int. const int* p — p is a pointer to const int. Both: const int* const p.
26
What is SFINAE and how does std::void_t simplify it?
Correct Answer
std::void_t<expr> evaluates to void when expr is valid, enabling cleaner SFINAE type traits without complex helper specializations
Explanation
template<class T, class = void> struct has_size : false_type {}; template<class T> struct has_size<T, void_t<decltype(T::size)>> : true_type {} detects if T has ::size.
27
What is the std::span type?
Correct Answer
A non-owning view over a contiguous sequence of objects, providing a unified interface for arrays, vectors, and C arrays
Explanation
std::span<T> (C++20) is like std::string_view but for any contiguous range. Passing span<int> accepts int[], vector<int>, and array<int,N>.
28
What is the std::ranges library (C++20)?
Correct Answer
A composable, lazy algorithm library that operates on ranges instead of iterator pairs, enabling pipeline syntax
Explanation
std::views::filter(isEven) | std::views::transform(square) creates a lazy view. Range algorithms use range objects directly without begin()/end() pairs.
29
What is the Pimpl (Pointer to Implementation) idiom?
Correct Answer
Hiding class implementation details behind an opaque pointer, reducing compile-time dependencies and improving ABI stability
Explanation
class Widget { struct Impl; unique_ptr<Impl> pImpl; }; moves implementation to a .cpp file. Changes to Impl don't recompile Widget's clients.
30
What is fold expression in C++17?
Correct Answer
A compile-time reduction of a parameter pack using a binary operator: (args + ...) or (... + args)
Explanation
template<typename... Ts> auto sum(Ts... args) { return (args + ...); } uses a right fold. (... + args) is a left fold. Eliminates recursive template specializations.
31
What is if constexpr in C++17?
Correct Answer
A compile-time conditional that discards the non-taken branch, enabling type-specific code in templates without SFINAE
Explanation
if constexpr (is_integral_v<T>) { ... } else { ... } — the else branch is not instantiated for integral T. Simpler than SFINAE for type-based branching.
32
What is a designated initializer (C++20)?
Correct Answer
Initializing struct members by name in aggregate initialization: Point p{.x = 1, .y = 2}
Explanation
C++20 designated initializers (struct Config cfg{.timeout = 30, .retries = 3}) improve readability and allow leaving other members zero-initialized.
33
What is the three-way comparison operator <=> (spaceship)?
Correct Answer
Returns std::strong_ordering (or weak/partial) indicating less, equal, or greater, auto-generating all six comparison operators
Explanation
auto operator<=>(const Point& o) const = default; auto-generates ==, !=, <, >, <=, >= using member-by-member comparison.
34
What is std::expected (C++23)?
Correct Answer
A type holding either an expected value T or an unexpected error E, avoiding exception overhead for error handling
Explanation
std::expected<int, std::error_code> open(path) returns either a valid int or an error_code. Allows functional error handling without exceptions.
35
What is CRTP used for beyond static polymorphism?
Correct Answer
Mixins that add functionality to derived classes (e.g., Comparable) and counting class instances via a static base counter
Explanation
CRTP enables mixins: template<class T> struct Printable { void print() { static_cast<T*>(this)->toString(); } }; Adding functionality without virtual dispatch.
36
What are C++20 concepts used for vs SFINAE in terms of readability?
Correct Answer
Concepts produce readable compiler error messages and cleaner constraint syntax, while SFINAE produces cryptic template instantiation errors
Explanation
template<Numeric T> T add(T a, T b) produces "T does not satisfy Numeric" errors. SFINAE equivalent produces a multi-line template instantiation failure trail.
37
What is coroutine_handle in C++20?
Correct Answer
A pointer to the coroutine frame with resume() and destroy() methods
Explanation
coroutine_handle<Promise> points to the coroutine frame. .resume() continues execution; .done() checks completion; .destroy() frees the frame.
38
What is the co_yield expression in C++20?
Correct Answer
Suspends the coroutine and produces a value to the caller, forming the basis for lazy generator coroutines
Explanation
co_yield x calls promise.yield_value(x), suspending the coroutine. Callers retrieve the value from the promise or via an awaitable returned by the coroutine.
39
What is std::jthread and how does it differ from std::thread?
Correct Answer
jthread is a thread that joins automatically in its destructor and supports cooperative cancellation via stop_token
Explanation
std::jthread (C++20) automatically calls join() in its destructor, preventing the "thread destructor calls std::terminate" bug. It also supports stop_source/stop_token for cancellation.
40
What is exception safety in C++ and what are the three guarantees?
Correct Answer
Basic: no leaks on exception; Strong: state unchanged on exception; Nothrow: never throws
Explanation
The three exception safety guarantees: Basic (no resource leaks), Strong (commit-or-rollback), Nothrow (noexcept). RAII provides basic safety automatically.
1
What is template metaprogramming (TMP)?
Correct Answer
Using the C++ template system to perform computations at compile time, producing constants or types
Explanation
TMP exploits template instantiation for compile-time computation (e.g., computing Fibonacci at compile time). C++17 constexpr and C++20 concepts reduce the need for TMP.
2
What are C++20 concepts?
Correct Answer
Named compile-time constraints on template type parameters, replacing complex SFINAE
Explanation
Concepts (requires Integral<T>) provide readable constraints on template parameters. They produce clear error messages and replace intricate enable_if/SFINAE patterns.
3
What are C++20 coroutines and how do they differ from C++ threads?
Correct Answer
Coroutines are suspendable functions managed by user code, with zero overhead compared to OS threads which have scheduling costs
Explanation
C++20 coroutines (co_await, co_yield, co_return) are stackless, suspending at specific points. They have minimal overhead vs OS threads and enable async I/O patterns.
4
What is the memory ordering model in C++11 atomic operations?
Correct Answer
Atomic operations have six orderings (relaxed, consume, acquire, release, acq_rel, seq_cst) controlling visibility guarantees between threads
Explanation
memory_order controls how atomic operations synchronize with other threads. seq_cst is safest but costliest. relaxed provides no synchronization. acquire-release establishes happens-before pairs.
5
What is type erasure in C++?
Correct Answer
A technique using polymorphism or templates to store and operate on objects of different types through a uniform interface without exposing the concrete type
Explanation
std::any, std::function, and std::variant use type erasure. std::function<void()> holds any callable without the caller knowing the concrete type.
6
What is the Curiously Recurring Template Pattern (CRTP)?
Correct Answer
A technique where a derived class is passed as a template argument to its own base class, enabling static polymorphism
Explanation
template<class T> class Base { }; class Derived : public Base<Derived> { }; enables the base to call derived methods without virtual dispatch overhead.
7
What is the One Definition Rule (ODR)?
Correct Answer
A program can have only one definition of each variable/function, but inline functions and templates may be defined in multiple translation units if all definitions are identical
Explanation
ODR violations (multiple different definitions of the same entity) cause undefined behavior. Inline, constexpr, and template definitions in headers are ODR-exempt if identical.
8
What is placement new in C++?
Correct Answer
Constructing an object at a pre-allocated memory location without additional allocation
Explanation
new (buffer) MyClass(args) constructs a MyClass in the already-allocated buffer. Used in memory pools and custom allocators. Requires explicit destructor call.
9
What is std::variant and when is it preferred over union?
Correct Answer
std::variant is a type-safe discriminated union that tracks which type is active and calls constructors/destructors correctly
Explanation
C unions don't track the active member and don't call constructors for non-trivial types. std::variant is type-safe, runs constructors/destructors, and enables std::visit.
10
What are C++20 modules and how do they differ from header files?
Correct Answer
Modules are binary interface units that expose only explicitly exported symbols, eliminating preprocessor include overhead and macro leakage
Explanation
C++20 modules (export module mylib;) compile once and provide a binary module interface. They improve build times, prevent macro pollution, and enforce encapsulation.
11
What is the std::allocator_traits and custom allocator pattern?
Correct Answer
allocator_traits provides a uniform interface for allocators, enabling containers to use custom memory strategies (pools, shared memory, NUMA)
Explanation
std::vector<int, PoolAlloc<int>> uses a custom allocator. allocator_traits<A> provides defaults for optional allocator members. Used in embedded, game, and HPC code.
12
What is the difference between deep in the compile pipeline between constexpr and consteval?
Correct Answer
constexpr can run at compile or runtime; consteval (immediate function) must always run at compile time and produces a compile error if called at runtime
Explanation
consteval functions are "immediate functions" — every call must produce a constant. If the argument is not a constant expression, compilation fails. constexpr may run at either time.
13
What is Address Sanitizer (ASan) in C++?
Correct Answer
A compile and runtime tool (-fsanitize=address) that detects memory errors: use-after-free, heap/stack buffer overflow, and more
Explanation
ASan instruments the binary with shadow memory to track valid memory regions. It catches bugs at runtime with precise diagnostics, invaluable during development.
14
What is undefined behavior sanitizer (UBSan)?
Correct Answer
A runtime tool (-fsanitize=undefined) that detects signed integer overflow, null pointer dereference, misaligned access, and other UB at runtime
Explanation
UBSan instruments code to detect UB at runtime. Compiling with -fsanitize=undefined catches issues that compilers may silently miscompile in production.
15
What is the aliasing rule and its impact on compiler optimization?
Correct Answer
The strict aliasing rule says pointers to different types cannot alias the same memory, allowing compilers to assume no interference and optimize aggressively
Explanation
If a compiler knows int* and float* can't alias, it reorders loads/stores freely. Violating strict aliasing (common in low-level code) is undefined behavior.
16
What is the ISO C++ hidden friend pattern?
Correct Answer
Defining friend functions inside the class body, making them only findable via ADL, preventing unintended lookup in regular unqualified calls
Explanation
Defining operator== as a friend inside the class hides it from normal lookup. It's only found via ADL (Argument-Dependent Lookup), preventing ambiguity with generic operators.
17
What is std::pmr (polymorphic memory resources, C++17)?
Correct Answer
A framework providing runtime-selectable memory allocators (pool, monotonic, unsynchronized) without changing container type via std::pmr::memory_resource
Explanation
std::pmr::vector<int> uses a pluggable allocator passed at construction. std::pmr::monotonic_buffer_resource enables arena allocation without changing container types.
18
What is Structured Binding Declarations interaction with custom types (C++17)?
Correct Answer
Any type can support structured bindings by specializing std::tuple_size, std::tuple_element, and providing get<N>
Explanation
Specializing tuple_size<MyType>, tuple_element<N, MyType>, and providing get<N>(MyType&) enables auto [a, b] = myValue for custom types.
19
What is the Itanium C++ ABI and why does it matter?
Correct Answer
The standard C++ ABI used by GCC, Clang, and most non-Windows compilers defining vtable layout, name mangling, and exception handling
Explanation
The Itanium ABI (despite the name, used on x86-64 Linux/macOS) ensures binary compatibility between compilers. MSVC uses its own ABI, which is why Windows mixing requires careful C-style extern "C" interfaces.
20
What is the "as-if" rule in C++ optimization?
Correct Answer
Compilers may transform code in any way as long as the observable behavior (I/O, volatile accesses, thread synchronization) is unchanged
Explanation
The as-if rule allows loop unrolling, function inlining, dead code elimination, and instruction reordering as long as the final observable behavior matches the abstract machine.