Title: Cpp Programming — LearnCoachAssist

Q: What are the four main principles of OOP in C++?
A: The four pillars of OOP are:
- Encapsulation – bundling data and methods together
- Abstraction – hiding complex implementation details
- Inheritance – deriving new classes from existing ones
- Polymorphism – using a single interface for different types

Q: What is a class in C++?
A: A class is a user-defined type that encapsulates data members and member functions. Defined with the class keyword:
class MyClass { public: int x; void show(); };

Q: What is the difference between a class and a struct in C++?
A: The only default difference is access control:
- class members are private by default
- struct members are public by default
Both can have methods, constructors, and inheritance.

Q: What is inheritance in C++?
A: Inheritance allows a derived class to inherit members from a base class:
class Dog : public Animal { };
This promotes code reuse and establishes an is-a relationship.

Q: What are virtual functions in C++?
A: A virtual function is declared with the virtual keyword in a base class, enabling runtime polymorphism:
virtual void speak() { }
Derived classes can override it, and the correct version is called via a base class pointer using the vtable.

Q: What is a pure virtual function?
A: A pure virtual function has no implementation in the base class and is declared as:
virtual void draw() = 0;
Any class containing a pure virtual function becomes an abstract class and cannot be instantiated directly.

Q: What is the purpose of the virtual destructor?
A: A virtual destructor ensures that when deleting an object through a base class pointer, the derived class destructor is called first:
virtual ~Base() { }
Without it, derived resources may leak.

Q: What is operator overloading in C++?
A: Operator overloading lets you redefine how operators work for user-defined types:
MyClass operator+(const MyClass& rhs) const { return MyClass(value + rhs.value); }
Most operators can be overloaded except ::, ., .*, and ?:.

Q: How do you overload the stream insertion operator?
A: The << operator is typically overloaded as a friend function:
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) { os << obj.data; return os; }

Q: What are namespaces in C++?
A: Namespaces group identifiers to avoid name collisions:
namespace Math { int add(int a, int b); }
Access with Math::add(1,2) or bring into scope with using namespace Math;.

Q: What is the std namespace?
A: The std namespace contains the entire C++ Standard Library, including containers, algorithms, and I/O classes. You access its members with std:: prefix, e.g., std::cout, std::vector.

Q: What is RAII in C++?
A: RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime:
- Resources are acquired in the constructor
- Resources are released in the destructor
This guarantees cleanup even if exceptions occur.

Q: What is a smart pointer?
A: A smart pointer is a class that manages a dynamically allocated object and automatically deletes it when no longer needed, following RAII. The main types are std::unique_ptr, std::shared_ptr, and std::weak_ptr.

Q: What is std::unique_ptr?
A: std::unique_ptr provides exclusive ownership of a dynamically allocated object:
auto p = std::make_unique<int>(42);
It cannot be copied, only moved. The object is deleted when the unique_ptr goes out of scope.

Q: What is std::shared_ptr?
A: std::shared_ptr allows shared ownership via reference counting:
auto p = std::make_shared<int>(42);
The managed object is deleted when the last shared_ptr owning it is destroyed. Use p.use_count() to check the count.

Q: What is std::weak_ptr and when is it used?
A: std::weak_ptr is a non-owning reference to an object managed by std::shared_ptr. It does not increment the reference count.
Used to break circular references. Call lock() to obtain a temporary shared_ptr.

Q: What are move semantics in C++?
A: Move semantics allow transferring resources from one object to another without copying. Enabled by rvalue references (&&) and implemented via a move constructor and move assignment operator. This greatly improves performance for temporary objects.

Q: What is an rvalue reference?
A: An rvalue reference, declared with &&, binds to temporary objects (rvalues):
void process(std::string&& s);
It enables move semantics by allowing you to "steal" resources from objects that are about to be destroyed.

Q: What does std::move do?
A: std::move is a cast that converts an lvalue into an rvalue reference, signaling that the object's resources may be moved from:
std::string b = std::move(a);
After the move, a is in a valid but unspecified state.

Q: What is a template in C++?
A: A template lets you write generic code that works with any type:
template<typename T> T max(T a, T b) { return (a > b) ? a : b; }
The compiler generates a specific version for each type used, a process called template instantiation.

Q: What is a class template?
A: A class template defines a blueprint for a class parameterized by types:
template<typename T> class Stack { std::vector<T> data; public: void push(T val); T pop(); };
Used as Stack<int> s;.

Q: What is template specialization?
A: Template specialization provides a custom implementation for a specific type:
template<> class Stack<bool> { /* optimized for bool */ };
There is full specialization (one specific type) and partial specialization (subset of parameters).

Q: What are the main STL container categories?
A: The STL containers fall into three categories:
- Sequence: vector, deque, list, array, forward_list
- Associative: set, map, multiset, multimap
- Unordered: unordered_set, unordered_map, etc.

Q: What is std::vector?
A: std::vector is a dynamic array that grows automatically:
std::vector<int> v = {1, 2, 3};
Key traits:
- O(1) random access
- Amortized O(1) push_back
- Contiguous memory layout

Q: What is std::map?
A: std::map is an ordered associative container storing key-value pairs in a red-black tree:
std::map<std::string, int> ages; ages["Alice"] = 30;
Keys are unique and kept in sorted order. Lookup is O(log n).

Q: What is std::unordered_map?
A: std::unordered_map stores key-value pairs in a hash table:
std::unordered_map<std::string, int> m;
Provides average O(1) lookup, insertion, and deletion. Keys are not sorted. Requires a hash function for custom key types.

Q: What is std::set?
A: std::set is an ordered container of unique elements implemented as a balanced BST:
std::set<int> s = {3, 1, 2};
Elements are always sorted. Insertion, lookup, and deletion are all O(log n).

Q: What is std::deque?
A: std::deque (double-ended queue) supports O(1) insertion and removal at both ends:
std::deque<int> d; d.push_front(1); d.push_back(2);
Unlike vector, it does not store elements in a single contiguous block.

Q: What is std::list in C++?
A: std::list is a doubly-linked list:
- O(1) insertion and deletion anywhere (given an iterator)
- No random access (no operator[])
- Higher memory overhead per element due to pointers

Q: What are iterators in C++?
A: Iterators are objects that act like generalized pointers, providing a uniform way to traverse containers:
for (auto it = v.begin(); it != v.end(); ++it) { /* use *it */ }
Categories include: input, output, forward, bidirectional, and random access.

Q: What is the difference between begin() and cbegin()?
A: begin() returns a mutable iterator allowing modification of elements.
cbegin() returns a const_iterator that provides read-only access:
auto it = v.cbegin(); // *it is const

Q: What is a reverse iterator?
A: A reverse iterator traverses a container from end to beginning:
for (auto rit = v.rbegin(); rit != v.rend(); ++rit) { std::cout << *rit; }
Obtained via rbegin() and rend() member functions.

Q: What is exception handling in C++?
A: C++ uses try-catch blocks for exception handling:
try { throw std::runtime_error("fail"); } catch (const std::exception& e) { std::cout << e.what(); }
Exceptions propagate up the call stack until a matching catch block is found.

Q: What is the std::exception hierarchy?
A: std::exception is the base class for standard exceptions. Key derived classes:
- std::runtime_error – runtime problems
- std::logic_error – logical errors
- std::bad_alloc – memory allocation failure
- std::out_of_range – index out of bounds

Q: What does the noexcept specifier do?
A: noexcept declares that a function will not throw exceptions:
void process() noexcept { }
If a noexcept function does throw, std::terminate is called. It helps the compiler optimize code and is important for move operations.

Q: What are lambda expressions in C++?
A: A lambda is an anonymous function object defined inline:
auto add = [](int a, int b) { return a + b; };
Syntax: [capture](params) -> return_type { body }
Lambdas can capture local variables by value or reference.

Q: What are the capture modes in a C++ lambda?
A: Lambda capture options:
- [x] – capture x by value
- [&x] – capture x by reference
- [=] – capture all used variables by value
- [&] – capture all by reference
- [=, &x] – all by value except x by reference

Q: What is std::function?
A: std::function is a general-purpose polymorphic function wrapper that can store any callable:
std::function<int(int,int)> fn = [](int a, int b){ return a+b; };
It can hold lambdas, function pointers, functors, and bind expressions.

Q: What is the Rule of Five in C++?
A: The Rule of Five states that if a class defines any of these, it should define all five:
- Destructor
- Copy constructor
- Copy assignment operator
- Move constructor
- Move assignment operator
This ensures correct resource management.

Q: What is the Rule of Zero?
A: The Rule of Zero says: if your class uses only RAII types (smart pointers, STL containers) for resource management, you should not define any special member functions. The compiler-generated defaults will be correct.

Q: What is the difference between deep copy and shallow copy?
A: A shallow copy duplicates pointers but not the pointed-to data, causing both objects to share the same memory.
A deep copy duplicates the actual data, giving each object its own independent copy. Deep copies are needed when a class manages raw dynamic memory.

Q: What is the auto keyword in C++11?
A: auto lets the compiler deduce the type from the initializer:
auto x = 42; // int
auto it = v.begin(); // iterator type
It reduces verbosity, especially with complex types like iterators and lambda expressions.

Q: What is a range-based for loop?
A: A range-based for loop iterates over all elements of a container:
for (const auto& elem : vec) { std::cout << elem; }
It works with any type that provides begin() and end() iterators. Use & to avoid copies.

Q: What is std::algorithm and name common algorithms?
A: The <algorithm> header provides generic functions that work with iterators:
- std::sort(v.begin(), v.end())
- std::find(v.begin(), v.end(), val)
- std::count_if(v.begin(), v.end(), pred)
- std::transform, std::accumulate, std::for_each

Q: What is the difference between std::array and std::vector?
A: std::array has a fixed size known at compile time and is stored on the stack:
std::array<int, 5> a = {1,2,3,4,5};
std::vector is dynamically sized and uses heap memory. Use array when the size is constant for better performance.

Q: What is std::pair and std::tuple?
A: std::pair holds two values: std::pair<int,string> p = {1, "hi"}; accessed via p.first, p.second.
std::tuple holds any number of values: auto t = std::make_tuple(1, 2.0, "hi"); accessed via std::get<0>(t).

Q: What is const correctness in C++?
A: Const correctness means using const wherever data should not be modified:
- const int x = 5; – immutable variable
- void foo(const std::string& s) – parameter not modified
- int getVal() const; – method doesn't modify the object
It prevents bugs and enables compiler optimizations.

Q: What is static_cast in C++?
A: static_cast performs compile-time type conversions with type checking:
double d = 3.14; int i = static_cast<int>(d);
Safer than C-style casts. Used for: numeric conversions, upcasting in inheritance, and void* to typed pointer conversions.

Q: What is the difference between stack and heap allocation?
A: Stack allocation is fast and automatic: int x = 5; Memory is freed when the scope ends.
Heap allocation uses new/delete: int* p = new int(5); delete p; It persists until explicitly freed. Prefer smart pointers over raw new/delete.

Q: What is an enum class (scoped enumeration)?
A: enum class (C++11) provides type-safe, scoped enumerations:
enum class Color { Red, Green, Blue };
Unlike plain enum, values don't implicitly convert to integers and don't pollute the enclosing namespace. Access with Color::Red.

Q: What is a constructor in C++?
A: A constructor is a special member function automatically invoked when an object is created. It has the same name as the class and no return type. If no constructor is provided, the compiler generates a default constructor.

Q: What is a default constructor?
A: A default constructor is one that can be called with no arguments. It is generated by the compiler only if no other constructor is declared. You can force its creation with = default:
MyClass() = default;

Q: What is a parameterized constructor?
A: A parameterized constructor accepts arguments used to initialize member variables:
class Point { int x,y; public: Point(int a, int b): x(a), y(b) {} };

Q: What is a copy constructor and when is it called?
A: A copy constructor initializes a new object as a copy of an existing one:
MyClass(const MyClass& other);
Called when: passing by value, returning by value, or explicitly initializing one object from another.

Q: What is a delegating constructor?
A: A delegating constructor calls another constructor of the same class in its initializer list:
Box(int s) : Box(s,s,s) {}
Box(int l,int w,int h) : ... {}
Prevents code duplication.

Q: What is a conversion constructor?
A: A conversion constructor is a non-explicit single-argument constructor that allows implicit conversion from that argument type to the class type. Marking it explicit blocks the implicit conversion.

Q: What is an initializer list?
A: An initializer list initializes members before the constructor body runs:
Point(int a,int b) : x(a), y(b) { }
Required for const members, references, and base class subobjects.

Q: What is the difference between initialization and assignment in constructors?
A: Initialization happens in the member initializer list (or default member initializer) and uses member initialization.
Assignment happens in the constructor body, where the member is first default-constructed then overwritten. Prefer initialization for efficiency.

Q: What are default member initializers (in-class member initializers)?
A: Default member initializers specify a default value for a member at its declaration:
int count = 0;
They apply when the member is not mentioned in the constructor's initializer list.

Q: What is a destructor and when is it called?
A: A destructor (~ClassName()) runs when an object's lifetime ends. It performs cleanup like releasing resources. It is called automatically on stack objects when their scope exits, and on heap objects via delete.

Q: What is a virtual function table (vtable)?
A: A vtable is a per-class table of pointers to virtual functions. Each object with virtuals carries a hidden vptr pointing to its class's vtable, enabling dynamic dispatch via the correct override at runtime.

Q: What is the vptr (virtual table pointer)?
A: Each object of a class with virtual functions contains a hidden vptr set by the constructor, pointing to that class's vtable. The vptr is what enables runtime polymorphism through base pointers/references.

Q: What is the difference between override and final specifiers?
A: override (C++11) asserts that a method overrides a base virtual; the compiler errors otherwise.
final prevents further overriding in derived classes (or prevents further derivation when applied to a class).

Q: What is an abstract class?
A: An abstract class contains at least one pure virtual function. It cannot be instantiated directly and serves as an interface or base for derived classes that provide implementations.

Q: What is an interface in C++?
A: C++ has no interface keyword; an interface is conventionally a class with only pure virtual functions and no data members (or only static const data). Derived classes must implement all pure virtuals to be instantiable.

Q: What is multiple inheritance in C++?
A: Multiple inheritance allows a class to inherit from more than one base class:
class C : public A, public B { };
It can cause the diamond problem, resolved with virtual inheritance.

Q: What is the diamond problem?
A: The diamond problem occurs with multiple inheritance when two bases share a common ancestor, giving the derived class two copies of that ancestor. Virtual inheritance ensures only one shared base subobject exists.

Q: What is virtual inheritance?
A: Virtual inheritance declares a base class as virtual in the derived class's base list:
class D : virtual public B {};
It guarantees that only one instance of B exists in the inheritance graph, solving the diamond problem.

Q: What is a using-declaration in C++?
A: A using declaration imports a name from a namespace or base class into the current scope:
using Base::foo; makes foo accessible directly in the derived class. using namespace std; brings all std names into scope.

Q: What is name hiding in inheritance?
A: Name hiding occurs when a derived class declares a name that matches one in the base: the base name is hidden in the derived class even if signatures differ. A using Base::name; declaration can unhide overloaded base functions.

Q: What are access specifiers in C++?
A: C++ has three access levels:
- public – accessible everywhere
- protected – accessible to the class, friends, and derived classes
- private – accessible only to the class and its friends
Default is private for class and public for struct.

Q: What is a friend function?
A: A friend function is a non-member function granted access to a class's private and protected members:
friend void print(const MyClass&);
Declared inside the class but defined outside. Breaks encapsulation, so use sparingly.

Q: What is a friend class?
A: A friend class can access the private and protected members of the class that declares it:
friend class Helper;
Useful for tightly coupled classes (e.g., iterators over a container).

Q: What is the static keyword in C++?
A: static has several meanings depending on context:
- Static local variable – persists across calls, initialized once
- Static class member – shared across all objects
- Static at file scope – internal linkage

Q: What is a static class member?
A: A static class member belongs to the class itself rather than any object. There is exactly one copy shared by all instances. It must be defined in a single translation unit:
int MyClass::count = 0;

Q: What is a static member function?
A: A static member function belongs to the class, not an instance. It has no this pointer and can only access static members:
static int getCount();
Called as MyClass::getCount().

Q: What is a const member function?
A: A const member function is declared with a trailing const:
int getX() const;
It promises not to modify the object's observable state and can be called on const objects.

Q: What is a mutable member?
A: A mutable member can be modified even inside const member functions:
mutable int cache_;
Useful for lazy initialization, caches, and mutexes.

Q: What is the this pointer?
A: this is a hidden pointer available in non-static member functions, pointing to the object on which the function was called. Its type is ClassName* const (or const ClassName* in const member functions).

Q: What is an abstract base class vs. concrete class?
A: An abstract class has at least one pure virtual function and cannot be instantiated.
A concrete class implements all inherited pure virtuals and can be instantiated.

Q: What is the difference between compile-time and runtime polymorphism?
A: Compile-time (static) polymorphism uses function/operator overloading and templates; the resolved call is determined at compile time.
Runtime (dynamic) polymorphism uses virtual functions and inheritance; the call is dispatched via the vtable at runtime.

Q: What is function overloading?
A: Function overloading lets you define multiple functions with the same name but different parameter lists in the same scope:
void print(int); void print(std::string);
Return type alone does not disambiguate overloads.

Q: What is operator overloading as a member vs. non-member?
A: A binary operator can be overloaded as a member (left operand is *this) or a non-member (often friend) taking both operands. The << stream operator is overloaded as a non-member so the left operand can be a stream.

Q: Which operators cannot be overloaded in C++?
A: You cannot overload: :: (scope resolution), . (member access), .* (member access through pointer), and ?: (ternary). You also cannot create new operator symbols.

Q: What is the copy-and-swap idiom?
A: Copy-and-swap implements assignment safely by copying the source and swapping with *this using a non-throwing swap. It provides strong exception safety and reuses copy/move logic.

Q: What is std::swap?
A: std::swap exchanges the values of two objects:
template<typename T> void swap(T& a, T& b) { T tmp = std::move(a); a = std::move(b); b = std::move(tmp); }
It is O(1) for many types via move semantics.

Q: What is perfect forwarding?
A: Perfect forwarding uses std::forward<T> with forwarding references (T&& in a template) to preserve the value category (lvalue/rvalue) of the original argument when passing to another function. It avoids unnecessary copies.

Q: What is a forwarding reference (universal reference)?
A: A forwarding reference is T&& in a deduced context (e.g., a function template parameter). It binds to both lvalues (becoming T&) and rvalues (becoming T), unlike a plain rvalue reference.

Q: What is std::forward?
A: std::forward<T>(arg) performs an unconditional cast back to the original value category that T deduced, enabling perfect forwarding. It does nothing if arg is an lvalue reference.

Q: What is the difference between std::move and std::forward?
A: std::move unconditionally casts to an rvalue reference (always treat as movable).
std::forward conditionally casts based on the template type T, preserving the original value category. Neither actually moves at runtime; both are casts.

Q: What is a reference and an lvalue reference?
A: A reference is an alias for another object. An lvalue reference (T&) binds to a named object (lvalue).
int x=5; int& r = x;
References cannot be reseated and must be initialized.

Q: What is a const reference and why is it useful?
A: A const reference (const T&) can bind to temporarys and avoids copying. It is the standard way to pass large objects to functions:
void print(const std::string& s);

Q: What is a dangling reference (dangling reference)?
A: A dangling reference refers to memory that is no longer valid, typically because the referenced object was destroyed. Never return a reference to a local variable:
int& bad() { int x; return x; } // undefined behavior

Q: What is a pointer and how does it differ from a reference?
A: A pointer is a variable that stores a memory address. Unlike a reference, a pointer can be null, reseated, and used with pointer arithmetic:
int* p = &x; *p = 10;

Q: What is a nullptr and why prefer it over NULL?
A: nullptr (C++11) is a keyword representing a null pointer constant of type std::nullptr_t. It avoids NULL's ambiguity (often an int 0) and improves overload resolution.

Q: What are const pointers and pointers to const?
A: - int* const p – const pointer: cannot be reseated, pointee can change
- const int* p – pointer to const: cannot modify pointee, pointer can be reseated
- const int* const p – both const

Q: What is a void pointer (void*)?
A: A void* is a pointer to unknown type. It can hold the address of any object but cannot be dereferenced directly. It must be cast to a typed pointer before use. Common in C APIs.

Q: What is const_cast in C++?
A: const_cast adds or removes const/volatile qualifiers. It is the only cast that can drop const:
const_cast<int&&gt;(x) = 5;
Modifying an originally const object through the result is undefined behavior.

Q: What is reinterpret_cast in C++?
A: reinterpret_cast performs low-level, implementation-defined bitwise conversions between pointer/integer types:
auto p = reinterpret_cast<void*>(0x1234);
Use only when you fully understand the platform's memory layout.

Q: What is dynamic_cast in C++?
A: dynamic_cast safely converts pointers/references within an inheritance hierarchy with runtime type checking (RTTI). It returns nullptr (or throws std::bad_cast for references) if the cast is invalid:
Derived* d = dynamic_cast<Derived*>(basePtr);

Q: What is C-style casting and why is it discouraged?
A: A C-style cast like (int)x tries a sequence of conversions: const_cast, static_cast, then reinterpret_cast. It is discouraged because its intent is unclear and it can silently perform dangerous conversions.

Q: What is a function pointer?
A: A function pointer stores the address of a function:
int (*fp)(int,int) = &add;
Can be invoked as fp(2,3). Useful for callbacks and C-style APIs. In C++ prefer std::function or lambdas.

Q: What is std::bind?
A: std::bind (in <functional>) creates a new callable by binding arguments to a function:
auto f = std::bind(add, 5, std::placeholders::_1);
f(3); // 8
Largely superseded by lambdas.

Q: What is std::ref and std::cref?
A: std::ref wraps a reference into a copyable object so a parameter template can bind to a reference rather than copy:
void f(int&); std::bind(f, std::ref(x));
std::cref does the same for a const reference.

Q: What is the std::chrono library?
A: std::chrono (in <chrono>) provides type-safe time durations and clocks:
auto start = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(start.time_since_epoch());

Q: What are the three main std::chrono clocks?
A: - std::system_clock – wall-clock time (since epoch)
- std::steady_clock – monotonic, never goes backward; ideal for intervals
- std::high_resolution_clock – smallest tick period available

Q: What is std::thread?
A: std::thread (in <thread>) launches a new OS thread running a callable:
std::thread t([]{ /* work */ }); t.join();
You must call either join() or detach() on every std::thread before destruction.

Q: What is std::async?
A: std::async runs a callable asynchronously and returns a std::future with the result:
auto fut = std::async(std::launch::async, []{ return 42; });
int v = fut.get();

Q: What is std::future and std::promise?
A: std::promise lets a producer set a value or exception; the matching std::future lets a consumer retrieve it:
std::promise<int> p; auto f = p.get_future();
p.set_value(42); int v = f.get();

Q: What is std::mutex?
A: std::mutex provides mutual exclusion for protecting shared data:
std::lock_guard<std::mutex> lk(m); /* critical section */
Always use RAII lock guards (lock_guard, unique_lock, scoped_lock) to avoid forgetting unlock().

Q: What is a deadlock?
A: A deadlock occurs when two or more threads each hold a lock and wait for a lock held by another, so none can proceed. Prevent deadlocks by acquiring locks in a fixed order or using std::scoped_lock (C++17) with deadlock-avoidance algorithms.

Q: What is a race condition?
A: A race condition occurs when the outcome of a program depends on the non-deterministic timing of concurrent accesses to shared data, producing different results on each run. Protect shared data with synchronization (mutex, atomics).

Q: What is std::atomic?
A: std::atomic (in <atomic>) provides lock-free thread-safe access to a value:
std::atomic<int> counter{0}; counter.fetch_add(1);
Operations are visible to other threads in a defined order (memory order).

Q: What is the difference between std::lock_guard and std::unique_lock?
A: std::lock_guard is a lightweight RAII lock with no extra features.
std::unique_lock additionally supports deferred locking, manual unlock, and ownership transfer (movable). Use unique_lock when you need that flexibility.

Q: What is a condition variable?
A: A std::condition_variable allows threads to wait until notified that a predicate is satisfied:
std::unique_lock<std::mutex> lk(m); cv.wait(lk, []{ return ready; });
Used to implement blocking queues and other synchronization patterns.

Q: What is the difference between new/delete and malloc/free?
A: - new/delete are operators that construct/destruct objects and are type-safe
- malloc/free are library functions that allocate raw bytes with no construction
delete calls the destructor; free does not. Avoid mixing them.

Q: What is placement new?
A: Placement new constructs an object at a specific preallocated memory address:
void* buf = ::operator new(sizeof(T));
T* obj = new (buf) T(args);
obj->~T(); ::operator delete(buf);
Used in custom allocators and memory pools.

Q: What is the difference between delete and delete[]?
A: delete deallocates memory for a single object and calls one destructor.
delete[] deallocates a C-style array allocated with new T[n] and calls the destructor for each element. Mismatching them is undefined behavior.

Q: What is a memory leak?
A: A memory leak occurs when dynamically allocated memory is never freed, gradually exhausting available memory. Prevent leaks by preferring RAII: smart pointers, containers, and other resource-managing classes instead of raw new/delete.

Q: What is the difference between compile-time and runtime?
A: Compile-time = when the compiler translates source code (errors, type checks, template instantiation).
Runtime = when the program is executing (logic, dynamic dispatch, exceptions). C++ strongly emphasizes zero-overhead abstractions resolved at compile time.

Q: What is the preprocessor and what does it do?
A: The preprocessor runs before compilation, performing text transformations based on directives:
- #include – inserts a file
- #define – creates a macro
- #ifdef/#ifndef – conditional compilation
- #pragma – implementation-defined hints

Q: What is the difference between #define and const?
A: #define is a textual macro with no type or scope; it can cause subtle bugs.
const (or constexpr) is a typed, scoped constant that participates in the type system. Prefer const/constexpr for constants.

Q: What is constexpr in C++?
A: constexpr declares that a variable or function can be evaluated at compile time:
constexpr int square(int x) { return x*x; }
constexpr int s = square(5);
In C++14+ it may contain loops and conditionals; C++20 added consteval (must be compile-time).

Q: What is the difference between const and constexpr?
A: const means the value cannot be modified at runtime.
constexpr guarantees the value can be evaluated at compile time. constexpr implies const for variables, but not vice versa.

Q: What is std::initializer_list?
A: std::initializer_list<T> represents a brace-enclosed list of values passed to a function or constructor:
void f(std::initializer_list<int> list);
f({1,2,3});
Allows users to write std::vector<int> v{1,2,3};.

Q: What is a uniform initialization (brace initialization)?
A: Brace initialization uses {} to initialize any object and prevents narrowing conversions:
int x{5}; // OK
int y{3.14}; // ERROR: narrowing
It is the recommended initialization syntax in modern C++.

Q: What is a narrowing conversion?
A: A narrowing conversion is one that can lose information (e.g., double to int, int64_t to int32_t). Brace initialization rejects narrowing conversions at compile time.

Q: What is std::variant (C++17)?
A: std::variant<int, std::string, double> is a type-safe union holding one of several alternative types:
std::variant<int,std::string> v = 42;
if (std::holds_alternative<int>(v)) std::get<int>(v);

Q: What is std::optional (C++17)?
A: std::optional<T> may or may not contain a value of type T:
std::optional<int> o = parseInt(s);
if (o) use(*o);
Replaces error-prone patterns using sentinels or out-parameters.

Q: What is std::any (C++17)?
A: std::any is a type-safe container for a single value of any copy-constructible type:
std::any a = 42; a = std::string("hi");
auto s = std::any_cast<std::string>(a);

Q: What is std::string_view (C++17)?
A: std::string_view is a non-owning reference to a contiguous sequence of characters:
void print(std::string_view sv);
Cheap to pass by value; avoids allocations and std::string copies.

Q: What is structured binding (C++17)?
A: Structured bindings unpack aggregates, pairs, tuples, and structured bindings:
auto [key, value] = *map.begin();
auto [x,y,z] = getPoint();
Replaces manual std::tie in many cases.

Q: What are if/switch init statements (C++17)?
A: You can initialize a variable in the condition of if or switch:
if (auto it = m.find(k); it != m.end()) { use(it->second); }
The variable lives until the end of the if/switch block.

Q: What are fold expressions (C++17)?
A: Fold expressions reduce a parameter pack over a binary operator:
template<typename... Args> auto sum(Args... args) { return (... + args); }
Supported operators include +, *, &&, ||, and the comma operator.

Q: What is a variadic template?
A: A variadic template accepts any number of template arguments:
template<typename... Args> void f(Args... args);
Expanded using parameter packs, often via recursion or fold expressions.

Q: What is a non-type template parameter?
A: A non-type template parameter is a value rather than a type:
template<int N> struct Buffer { char data[N]; };
Buffer<128> buf;
From C++20 it can be a class type with operator<=> (literal class).

Q: What is template metaprogramming?
A: Template metaprogramming uses templates to perform computation at compile time. Examples include std::tuple, std::integral_constant, and SFINAE. It produces highly optimized code but can be hard to read.

Q: What is SFINAE?
A: SFINAE (Substitution Failure Is Not An Error) means that when substituting template parameters fails, the compiler silently removes that overload rather than aborting. It's the basis of type traits and many compile-time checks.

Q: What are std::enable_if and std::void_t?
A: std::enable_if<Cond, T> yields T when Cond is true, and is otherwise ill-formed (SFINAE):
template<typename T> typename std::enable_if<std::is_integral<T>::value, T>::type f(T);
std::void_t<...> detects valid expressions in trait detectors.

Q: What are concepts (C++20)?
A: Concepts are named compile-time predicates that constrain template parameters:
template<std::integral T> T add(T a, T b) { return a+b; }
They replace most SFINAE boilerplate with clear, readable constraints.

Q: What is the three-way comparison operator <=> (C++20)?
A: <=> (the spaceship operator) returns a comparison category type indicating ordering:
auto cmp = a <=> b; if (cmp < 0) ...
With = default the compiler generates all six relational operators.

Q: What are coroutines (C++20)?
A: C++20 coroutines are functions that can be suspended and resumed using co_await, co_yield, and co_return. They are used to build generators, async I/O, and lazy computations without callback chains.

Q: What is std::span (C++20)?
A: std::span<T> is a non-owning view over a contiguous sequence, like a safe pointer-plus-size pair:
void process(std::span<int> s);
process(std::vector<int>{1,2,3});

Q: What is std::format (C++20)?
A: std::format provides Python-like, type-safe text formatting:
std::string s = std::format("Hello, {}! You are {:.2f}", name, age);
Replaces printf with a type-safe, extensible alternative.

Q: What are modules (C++20)?
A: Modules replace header files with faster, more isolated translation units:
export module math;
export int add(int a,int b){return a+b;}
Consumers use import math;. Avoids macro leakage and macro-order issues.

Q: What is std::filesystem?
A: std::filesystem (C++17) provides portable paths, files, and directories:
for (auto& e : std::filesystem::directory_iterator(".")) std::cout << e.path() << '\n';

Q: What is an assertion and assert()?
A: An assertion is a runtime check of an invariant. assert(expr) (in <cassert>) aborts the program with a message if expr is false. Define NDEBUG to disable assertions in release builds.

Q: What is static_assert?
A: static_assert(cond, "message") performs a compile-time assertion. The program is ill-formed if the condition is false:
static_assert(sizeof(void*) == 8, "Requires 64-bit");
Useful for enforcing type traits and alignment requirements.

Q: What is undefined behavior (UB)?
A: Undefined behavior is anything the standard does not define: signed integer overflow, null-pointer dereference, reading uninitialized memory, out-of-bounds access, etc. The compiler may assume UB never happens and optimize accordingly.

Q: What is implementation-defined behavior?
A: Implementation-defined behavior must be documented by the implementation (compiler/library) but is not specified by the standard. Examples: sizeof(int), byte order, and the value of a char after overflow.

Q: What is the One Definition Rule (ODR)?
A: The One Definition Rule states that any program must have exactly one definition of each non-inline function or variable across all translation units. Inline functions and class definitions may appear in multiple translation units identically.

Q: What is the difference between declaration and definition?
A: A declaration introduces a name and its type:
extern int x; void foo(int);
A definition provides the storage/function body:
int x = 5; void foo(int) { }
Definitions are also declarations; declarations may appear many times.

Q: What are translation units and header files?
A: A translation unit is a source file plus the result of including all its headers, after preprocessing. Header files typically contain declarations and inline definitions, included via #include in many translation units.

Q: What is an include guard?
A: Include guards (or #pragma once) prevent a header from being processed more than once per translation unit:
#ifndef FOO_H
#define FOO_H
// ...
#endif
Avoids multiple-definition errors from repeated inclusion.

Q: What is the difference between std::string and C-style strings?
A: std::string is a class managing a heap-allocated, resizable character sequence with bounds-checked operations.
A C-style string is a const char* pointing to a null-terminated array with no size and no safety. Prefer std::string in C++.

Q: What are std::string's main operations?
A: Common std::string operations include:
- size()/length(), empty()
- substr(pos, len), find(s), replace(...)
- append(s), operator+
- Access via operator[] or at() (bounds-checked)

Q: What is std::stringstream?
A: std::stringstream is an in-memory string buffer supporting <</>> like streams:
std::stringstream ss; ss << "x=" << 42; auto s = ss.str();
Useful for parsing and building strings.

Q: What is std::regex?
A: std::regex (in <regex>) is the standard library's regular expression support. Use std::regex_match, std::regex_search, and std::regex_replace with std::smatch for results. Note: it is often considered slow and unwieldy.

Q: What is a stack unwinding?
A: Stack unwinding is the process of destroying automatic objects in each stack frame as an exception propagates toward a catch block. It makes RAII cleanup reliable. If no handler is found, std::terminate is called.

Q: What is the difference between throw by value and catch by const reference?
A: Throw by value allows the thrower to construct a meaningful exception object.
Catch by const reference (catch (const std::exception& e)) avoids slicing and unnecessary copies and is the standard guideline (Herb Sutter).

Q: What is std::terminate?
A: std::terminate is called when:
- An exception escapes a noexcept function
- An exception is thrown during stack unwinding
- No catch is found
It calls the current std::terminate_handler, defaulting to std::abort.

Q: What is exception safety?
A: Exception safety describes guarantees a function offers if an exception occurs:
- Nothrow – never throws
- Strong – either succeeds or has no effect
- Basic – no leaks, object still usable
- No – anything can happen

Q: What is the difference between throw and noexcept(false)?
A: A function declared noexcept(false) explicitly states it may throw. Plain noexcept is the default for most cases that should not throw. Use noexcept for move operations, destructors, and swap.

Q: What is a vtable and how does it differ from a vptr?
A: The vtable is a static, per-class array of virtual function pointers. Each object has a vptr pointing to its class's vtable. The compiler generates the vtable at compile time; the vptr is set by every constructor.

Q: What is an inline function?
A: An inline function is a hint to the compiler to insert the function body at the call site to avoid call overhead. Modern compilers ignore the hint and decide automatically. Inline functions must be defined in every translation unit that uses them.

Q: What is constexpr vs inline?
A: constexpr indicates a function can be evaluated at compile time when given constant expressions.
inline allows the function to be defined in multiple translation units without violating the ODR.
A function can be both inline constexpr.

Q: What is the volatile keyword?
A: volatile tells the compiler that a variable's value may change out of the compiler's control (e.g., memory-mapped I/O). It disables certain optimizations. It does not provide thread-safety – use std::atomic for that.

Q: What is the difference between const volatile and volatile?
A: const volatile means the program cannot modify the variable, but something else might (e.g., a hardware register readable but not writable). volatile alone allows the program to modify it as well.

Q: What is std::bit_cast (C++20)?
A: std::bit_cast<To>(from) reinterprets the object representation of from as To at compile time with well-defined results:
float f = 1.0f; auto b = std::bit_cast<std::uint32_t>(f);
Replaces memcpy-based type punning.

Q: What is std::launder (C++17)?
A: std::launder(p) obtains a pointer to an object occupying memory whose lifetime was revived by placement new. It blocks the compiler from assuming the pointer still refers to the old object.