C++_2

THIS IS NOTES FOR C++_2

























1. What is C++?


C++ is a general-purpose, object-oriented programming language with low-level memory manipulation capabilities. It supports features like classes, templates, and STL, making it versatile for system, game, and application development.



2. What are the main features of C++?


C++ offers object-oriented programming, generic programming via templates, low-level memory control, and the Standard Template Library (STL). Its performance, flexibility, and multi-paradigm support make it suitable for diverse applications.



3. What is the difference between C and C++?


C++ extends C with object-oriented features like classes, inheritance, and polymorphism, plus templates and STL. C is procedural, lacks these abstractions, and has limited standard library support.



4. What is object-oriented programming (OOP) in C++?


OOP in C++ organizes code into objects using classes, supporting encapsulation, inheritance, polymorphism, and abstraction. It enhances modularity and reusability, like `class Car { public: void drive(); }`.



5. What is a class in C++?


A class is a user-defined type defining properties (data members) and behaviors (member functions), like `class Person { string name; void speak(); }`. It serves as a blueprint for objects.



6. What is an object in C++?


An object is an instance of a class, holding specific data and capable of invoking class methods. For example, `Person p; p.name



7. What is the difference between a class and a struct in C++?


A class defaults to private access for members, while a struct defaults to public. Otherwise, they’re functionally equivalent, both supporting data and methods, with `class` preferred for OOP.



8. What is a constructor in C++?


A constructor is a special member function called when an object is created, initializing its data. It has the same name as the class, like `Person(string n) { name



9. What is a default constructor in C++?


A default constructor takes no parameters or has default arguments, provided automatically if no constructors are defined. It initializes members to default values, like `Person() { name



10. What is a copy constructor in C++?


A copy constructor initializes an object using another object of the same class, like `Person(const Person& other) { name



11. What is a destructor in C++?


A destructor, named `~ClassName()`, cleans up resources when an object is destroyed, like closing files. It’s automatically called when an object goes out of scope.



12. What is the `this` pointer in C++?


`this` is a pointer to the current object, used to access instance members or disambiguate parameters. For example, `void setName(string name) { this->name



13. What is encapsulation in C++?


Encapsulation hides a class’s internal data, exposing only necessary interfaces via public methods. It’s achieved with `private` or `protected` members and public getters/setters for data protection.



14. What is inheritance in C++?


Inheritance allows a class to inherit members from a base class using `:`, like `class Dog : public Animal`. It promotes code reuse and establishes an “is-a” relationship.



15. What are access specifiers in C++?


Access specifiers (`public`, `private`, `protected`) control member visibility. `public` is accessible everywhere, `private` within the class, and `protected` within the class and subclasses.



16. What is the difference between public, private, and protected inheritance?


Public inheritance retains base class access levels, protected makes public members protected, and private makes all inherited members private. For example, `class Derived : protected Base` restricts access.



17. What is multiple inheritance in C++?


Multiple inheritance allows a class to inherit from multiple base classes, like `class Child : public Parent1, public Parent2`. It can lead to the diamond problem, resolved with virtual inheritance.



18. What is the diamond problem in C++?


The diamond problem occurs when a class inherits from two classes sharing a common base, causing ambiguity. Virtual inheritance, like `virtual public Base`, ensures a single base instance.



19. What is virtual inheritance in C++?


Virtual inheritance ensures a single instance of a base class is shared in multiple inheritance, using `virtual`, like `class B : virtual public A`. It resolves the diamond problem.



20. What is polymorphism in C++?


Polymorphism allows objects to be treated as instances of a base class, with runtime polymorphism via virtual functions or compile-time via overloading. It enables flexible behavior.



21. What is a virtual function in C++?


A virtual function, declared with `virtual`, enables runtime polymorphism by allowing derived classes to override it. For example, `virtual void display() {}` ensures the correct method is called.



22. What is a pure virtual function in C++?


A pure virtual function, declared as `virtual void func()



23. What is an abstract class in C++?


An abstract class contains at least one pure virtual function and cannot be instantiated. It serves as a base for derived classes, like `class Shape { virtual void draw()



24. What is function overloading in C++?


Function overloading allows multiple functions with the same name but different parameter lists, like `void print(int)` and `void print(double)`. The compiler selects based on arguments.



25. What is operator overloading in C++?


Operator overloading redefines operators like `+` for user-defined types, like `Complex operator+(const Complex& other)`. It enhances readability but requires careful implementation.







26. What is the `friend` keyword in C++?


`friend` grants a function or class access to a class’s private members, like `friend void print(Person& p)`. It’s used sparingly to maintain encapsulation.



27. What is a static member in C++?


A static member belongs to the class, not objects, shared across instances, like `static int count`. It’s initialized outside the class and accessed via `ClassName::member`.



28. What is a static member function in C++?


A static member function, declared `static`, belongs to the class and can access only static members. It’s called without an object, like `ClassName::func()`.



29. What is the `const` keyword in C++?


`const` ensures a variable or member function doesn’t modify state, like `int getValue() const`. It’s used for immutability and safe method declarations.



30. What is a `const` member function in C++?


A `const` member function, declared with `const`, promises not to modify the object, like `void display() const`. It’s callable on `const` objects and ensures safety.



31. What is a pointer in C++?


A pointer is a variable storing a memory address, like `int* ptr



32. What is a reference in C++?


A reference is an alias for a variable, like `int& ref



33. What is the difference between a pointer and a reference?


A pointer stores a memory address and can be null or reassigned, while a reference is an alias, always bound to an existing variable. Pointers are more flexible but riskier.



34. What is the `new` operator in C++?


`new` allocates memory on the heap and returns a pointer, like `int* ptr



35. What is the `delete` operator in C++?


`delete` deallocates heap memory allocated by `new`, like `delete ptr`. It prevents memory leaks, with `delete[]` used for arrays, like `delete[] arr`.



36. What is a memory leak in C++?


A memory leak occurs when dynamically allocated memory isn’t freed, like forgetting `delete ptr`. It reduces available memory, potentially causing program crashes.



37. What is a dangling pointer in C++?


A dangling pointer points to memory that’s been freed or gone out of scope, like `int* ptr



38. What is the `nullptr` in C++?


`nullptr`, introduced in C++11, is a type-safe null pointer constant replacing `NULL`. It avoids ambiguity in function overloading, like `func(int*)` vs `func(int)`.



39. What is a smart pointer in C++?


A smart pointer, like `std::unique_ptr` or `std::shared_ptr`, manages dynamic memory automatically, freeing it when no longer needed. It prevents leaks and simplifies memory management.



40. What is `std::unique_ptr` in C++?


`std::unique_ptr`, introduced in C++11, owns a single object, ensuring it’s deleted when the pointer goes out of scope. It’s non-copyable but movable, like `unique_ptr p



41. What is `std::shared_ptr` in C++?


`std::shared_ptr` allows multiple pointers to share ownership of an object, deleting it when the last pointer is destroyed. It uses reference counting, like `shared_ptr p



42. What is `std::weak_ptr` in C++?


`std::weak_ptr` references a `shared_ptr` object without owning it, avoiding circular references. It’s used to break cycles, checking validity via `lock()` before access.



43. What is the Standard Template Library (STL) in C++?


The STL is a collection of templates for containers (`vector`, `map`), algorithms (`sort`, `find`), and iterators. It provides reusable, efficient data structures and functions.



44. What are the main components of the STL?


The STL includes containers (e.g., `vector`, `set`), algorithms (e.g., `sort`, `reverse`), iterators for traversal, and function objects (functors). These components work together for generic programming.



45. What is a `std::vector` in C++?


`std::vector` is a dynamic array container, resizing automatically, like `vector v



46. What is a `std::list` in C++?


`std::list` is a doubly-linked list container, supporting fast insertions/deletions anywhere, like `list l



47. What is a `std::map` in C++?


`std::map` is an associative container storing key-value pairs in sorted order, like `map m`. It uses a red-black tree for logarithmic-time operations.



48. What is a `std::unordered_map` in C++?


`std::unordered_map`, introduced in C++11, stores key-value pairs in a hash table, offering average constant-time access. It’s unsorted, unlike `std::map`, like `unordered_map um`.



49. What is a `std::set` in C++?


`std::set` is a container of unique, sorted elements, like `set s



50. What is a `std::unordered_set` in C++?


`std::unordered_set` stores unique elements in a hash table, offering average constant-time operations, like `unordered_set us`. It’s unsorted, unlike `std::set`.







51. What is the difference between `std::map` and `std::unordered_map`?


`std::map` maintains sorted keys with logarithmic-time operations, while `std::unordered_map` uses a hash table for average constant-time access but no ordering. Choose based on sorting needs.



52. What is an iterator in C++?


An iterator is an object for traversing STL containers, like `vector::iterator it`. It supports operations like `*it` for access and `++it` for movement.



53. What are the types of iterators in C++?


C++ iterators include input, output, forward, bidirectional, and random-access iterators. For example, `vector` uses random-access, while `list` uses bidirectional, determining traversal capabilities.



54. What is a const_iterator in C++?


A `const_iterator`, like `vector::const_iterator`, allows read-only access to container elements. It’s used with `const` containers or to ensure no modifications.



55. What is the `begin()` and `end()` in STL containers?


`begin()` returns an iterator to the first element, and `end()` points past the last element, like `v.begin()` and `v.end()`. They define the range for iteration.



56. What is an algorithm in the STL?


STL algorithms are generic functions for operations like sorting (`std::sort`) or searching (`std::find`), operating on container ranges via iterators. They promote code reuse.



57. What is `std::sort` in C++?


`std::sort` sorts a range of elements, like `sort(v.begin(), v.end())`, using introsort (a hybrid algorithm). It’s customizable with a comparator, like `sort(v.begin(), v.end(), greater())`.



58. What is `std::find` in C++?


`std::find` searches a range for a value, returning an iterator to the first occurrence, like `find(v.begin(), v.end(), 5)`. It returns `end()` if not found.



59. What is a functor in C++?


A functor is a class with an overloaded `operator()`, like `struct Compare { bool operator()(int a, int b) { return a < b; } }`. It’s used in STL algorithms or containers.



60. What is a template in C++?


A template is a blueprint for generic classes or functions, like `template T add(T a, T b)`. It enables type-safe, reusable code without duplication.



61. What is a function template in C++?


A function template generalizes a function for different types, like `template T max(T a, T b)`. The compiler generates specific versions based on usage.



62. What is a class template in C++?


A class template defines a generic class, like `template class Box { T value; }`. It’s instantiated with specific types, like `Box`.



63. What is template specialization in C++?


Template specialization provides a custom implementation for a specific type, like `template<> class Box`. It overrides the generic template for that type.



64. What is the `typename` keyword in C++?


`typename` disambiguates dependent types in templates, like `template using Iter



65. What is a variadic template in C++?


A variadic template, introduced in C++11, handles a variable number of arguments, like `template void print(Args... args)`. It’s used with recursion or fold expressions.



66. What is a fold expression in C++?


A fold expression, introduced in C++17, simplifies variadic template operations, like `(args + ...)` to sum arguments. It reduces recursive code for variadic templates.



67. What is exception handling in C++?


Exception handling manages runtime errors using `try`, `catch`, and `throw`, like `try { throw 1; } catch(int e) {}`. It prevents crashes and ensures graceful recovery.



68. What is the `throw` keyword in C++?


`throw` raises an exception, like `throw std::runtime_error(\"Error\")`. It transfers control to the nearest `catch` block handling the exception type.



69. What is a `try-catch` block in C++?


A `try` block encloses code that might throw exceptions, and `catch` handles them, like `catch(std::exception& e) {}`. Multiple `catch` blocks handle different types.



70. What is the `std::exception` class in C++?


`std::exception` is the base class for standard exceptions, providing a `what()` method for error messages. Derived classes include `runtime_error` and `logic_error`.



71. What is a custom exception in C++?


A custom exception is a user-defined class deriving from `std::exception`, like `class MyError : public std::exception`. It’s used for application-specific errors.



72. What is `noexcept` in C++?


`noexcept`, introduced in C++11, specifies that a function doesn’t throw exceptions, like `void func() noexcept`. It optimizes code and informs the compiler.



73. What is a stack unwinding in C++?


Stack unwinding occurs when an exception is thrown, destroying local objects in reverse order until a `catch` is found. It ensures proper cleanup of resources.



74. What is RAII in C++?


RAII (Resource Acquisition Is Initialization) ties resource management to object lifetimes, like files in `std::fstream`. Resources are acquired in constructors and released in destructors.



75. What is a `std::string` in C++?


`std::string` is a class for managing dynamic strings, like `string s







76. What is the difference between C-style strings and `std::string`?


C-style strings are null-terminated `char` arrays, like `char str[]



77. What is a `std::array` in C++?


`std::array`, introduced in C++11, is a fixed-size container with STL integration, like `array arr



78. What is a `std::tuple` in C++?


`std::tuple`, introduced in C++11, stores a fixed-size collection of heterogeneous values, like `tuple t



79. What is structured binding in C++?


Structured binding, introduced in C++17, unpacks aggregates like `tuple` or `struct`, like `auto [x, y]



80. What is a lambda expression in C++?


A lambda expression, introduced in C++11, is an anonymous function, like `[



81. What is the capture clause in a C++ lambda?


The capture clause, like `[



82. What is `std::function` in C++?


`std::function`, introduced in C++11, is a type-erased wrapper for callable objects, like `function f



83. What is a `std::bind` in C++?


`std::bind`, introduced in C++11, creates a function object by binding arguments, like `auto f



84. What is multithreading in C++?


Multithreading allows concurrent execution of threads, improving performance for parallel tasks. C++11 introduced `std::thread`, `std::mutex`, and other tools for thread management.



85. What is `std::thread` in C++?


`std::thread`, introduced in C++11, creates a new thread, like `thread t(func)`. It executes `func` concurrently, joined via `t.join()` or detached with `t.detach()`.



86. What is the difference between `join()` and `detach()` in `std::thread`?


`join()` waits for a thread to finish, blocking the calling thread, while `detach()` lets it run independently, potentially outliving the main thread. `join()` ensures cleanup.



87. What is a `std::mutex` in C++?


`std::mutex` provides mutual exclusion, ensuring only one thread accesses a resource, like `mutex mtx; mtx.lock()`. It’s used for thread-safe critical sections.



88. What is a `std::lock_guard` in C++?


`std::lock_guard`, introduced in C++11, is an RAII wrapper for `mutex`, automatically unlocking on scope exit, like `lock_guard guard(mtx)`. It prevents deadlocks from forgotten unlocks.



89. What is a `std::unique_lock` in C++?


`std::unique_lock` is a flexible lock for `mutex`, allowing manual locking/unlocking, like `unique_lock lock(mtx, defer_lock)`. It’s used with condition variables or timeouts.



90. What is a `std::condition_variable` in C++?


`std::condition_variable` enables thread synchronization, allowing threads to wait or signal, like `cv.wait(lock)`. It’s used with `unique_lock` for producer-consumer patterns.



91. What is a deadlock in C++?


A deadlock occurs when threads hold locks and wait for each other’s locks, stalling indefinitely. It’s prevented by lock ordering or using `std::lock` for multiple mutexes.



92. What is a race condition in C++?


A race condition occurs when threads access shared data concurrently, causing unpredictable results. It’s prevented with `mutex`, atomic operations, or thread-safe designs.



93. What is `std::atomic` in C++?


`std::atomic`, introduced in C++11, provides thread-safe atomic operations, like `atomic counter`. It ensures operations like `++counter` are indivisible, avoiding race conditions.



94. What is a `std::future` in C++?


`std::future`, introduced in C++11, represents a future result of an asynchronous task, like `future f



95. What is a `std::promise` in C++?


`std::promise` delivers a value or exception to a `std::future`, like `promise p; p.set_value(42)`. It’s used for asynchronous communication between threads.



96. What is `std::async` in C++?


`std::async`, introduced in C++11, runs a function asynchronously, returning a `std::future`, like `auto f



97. What is the difference between `std::thread` and `std::async`?


`std::thread` creates a thread with manual management, while `std::async` abstracts thread or task execution, returning a `future`. `std::async` is higher-level and often safer.



98. What is a `constexpr` in C++?


`constexpr`, introduced in C++11, specifies that a function or variable is evaluated at compile-time, like `constexpr int square(int x) { return x * x; }`. It improves performance.



99. What is the difference between `const` and `constexpr`?


`const` ensures runtime immutability, while `constexpr` ensures compile-time evaluation, like `constexpr int x



100. What is `auto` in C++?


`auto`, enhanced in C++11, deduces a variable’s type from its initializer, like `auto x







101. What is `decltype` in C++?


`decltype`, introduced in C++11, deduces an expression’s type, like `decltype(x) y



102. What is a range-based for loop in C++?


A range-based for loop, introduced in C++11, iterates over containers, like `for(int x : vector{1, 2, 3})`. It simplifies iteration without explicit iterators.



103. What is `std::move` in C++?


`std::move`, introduced in C++11, enables move semantics, casting an object to an rvalue, like `vector v2



104. What is move semantics in C++?


Move semantics, introduced in C++11, transfers resources from one object to another, like `vector`’s move constructor. It avoids copying, using rvalue references (`&&`).



105. What is an rvalue reference in C++?


An rvalue reference, introduced in C++11, binds to temporary objects, like `void func(int&& x)`. It enables move semantics and perfect forwarding in templates.



106. What is perfect forwarding in C++?


Perfect forwarding, using `std::forward` and rvalue references, preserves an argument’s value category (lvalue/rvalue) in templates, like `template void func(T&& arg)`. It ensures efficient argument passing.



107. What is `std::forward` in C++?


`std::forward`, introduced in C++11, forwards arguments while preserving their value category, like `std::forward(arg)`. It’s used in templates for perfect forwarding.



108. What is a copy constructor vs move constructor?


A copy constructor copies an object’s data, like `Class(const Class&)`, while a move constructor transfers resources, like `Class(Class&&)`. Move is faster for temporaries.



109. What is the rule of three in C++?


The rule of three states that if a class defines a destructor, copy constructor, or copy assignment operator, it likely needs all three. It ensures proper resource management.



110. What is the rule of five in C++?


The rule of five, extending the rule of three, includes move constructor and move assignment operator, like `Class(Class&&)` and `Class& operator



111. What is the rule of zero in C++?


The rule of zero advises avoiding custom destructors, copy/move operations by using smart pointers and STL containers. It simplifies classes, letting the compiler handle resource management.



112. What is a `virtual` destructor in C++?


A `virtual` destructor ensures proper cleanup of derived class objects via base class pointers, like `virtual ~Base()`. It prevents undefined behavior during polymorphic deletion.



113. What is `override` in C++?


`override`, introduced in C++11, ensures a function overrides a virtual function, like `void func() override`. It catches errors at compile-time if signatures don’t match.



114. What is `final` in C++?


`final`, introduced in C++11, prevents a class from being inherited (`class X final`) or a virtual function from being overridden (`virtual void func() final`). It enforces design constraints.



115. What is a `static_cast` in C++?


`static_cast` performs type conversions with compile-time checks, like `static_cast(int)`. It’s safer than C-style casts, used for related types or explicit conversions.



116. What is a `dynamic_cast` in C++?


`dynamic_cast` performs runtime type-safe casting for polymorphic types, like `dynamic_cast(base)`. It returns `nullptr` if the cast fails, requiring RTTI.



117. What is a `const_cast` in C++?


`const_cast` adds or removes `const` or `volatile` qualifiers, like `const_cast(const_ptr)`. It’s used rarely, often for legacy APIs, and risks undefined behavior if misused.



118. What is a `reinterpret_cast` in C++?


`reinterpret_cast` performs low-level, unsafe type conversions, like `reinterpret_cast(ptr)`. It’s used for unrelated types, like pointers, but requires extreme caution.



119. What is RTTI in C++?


Run-Time Type Information (RTTI) enables type identification at runtime, like `typeid` or `dynamic_cast`. It’s used for polymorphic types but adds overhead, so use sparingly.



120. What is the `typeid` operator in C++?


`typeid`, part of RTTI, returns type information, like `typeid(obj).name()`. It’s used to identify an object’s type at runtime, requiring polymorphic types for accuracy.



121. What is inline function in C++?


An `inline` function, declared with `inline`, suggests the compiler to insert its code at the call site, like `inline int add(int a, int b)`. It reduces function call overhead.



122. What is the `explicit` keyword in C++?


`explicit` prevents implicit conversions via constructors, like `explicit Class(int x)`. It avoids unintended type conversions, improving type safety, introduced in C++11.



123. What is a `namespace` in C++?


A `namespace` groups identifiers to avoid name conflicts, like `namespace MyLib { int x; }`. It’s accessed via `MyLib::x` or `using namespace MyLib`.



124. What is `using` declaration in C++?


A `using` declaration imports a specific name, like `using std::cout;`, avoiding fully qualified names. It’s safer than `using namespace` to prevent namespace pollution.



125. What is anonymous namespace in C++?


An anonymous namespace, like `namespace { int x; }`, limits names to the current translation unit. It’s equivalent to `static` for file-local variables or functions.







126. What is `std::pair` in C++?


`std::pair` holds two values of different types, like `pair p



127. What is `std::optional` in C++?


`std::optional`, introduced in C++17, represents a value that may or may not exist, like `optional opt



128. What is `std::variant` in C++?


`std::variant`, introduced in C++17, stores one of several types, like `variant v



129. What is `std::any` in C++?


`std::any`, introduced in C++17, stores any type-safe value, like `any a



130. What is a `std::filesystem` in C++?


`std::filesystem`, introduced in C++17, provides file system operations, like `fs::path` or `fs::create_directory`. It’s portable, replacing platform-specific file handling.



131. What is a `std::chrono` in C++?


`std::chrono`, introduced in C++11, handles time operations, like `chrono::milliseconds` or `chrono::system_clock`. It’s used for timing, durations, or delays.



132. What is a `std::regex` in C++?


`std::regex`, introduced in C++11, supports regular expressions, like `regex r(\"\\\\d+\")` for digit matching. It’s used with `regex_match` or `regex_search` for pattern processing.



133. What is a `std::bitset` in C++?


`std::bitset` represents a fixed-size sequence of bits, like `bitset<8> b(\"1010\")`. It’s used for compact storage and bitwise operations, like `b.flip()`.



134. What is `std::valarray` in C++?


`std::valarray` is a container for numerical computations, like `valarray v



135. What is a design pattern in C++?


A design pattern is a reusable solution to common software problems, like Singleton or Factory. In C++, they leverage features like templates and polymorphism for implementation.



136. What is the Singleton pattern in C++?


The Singleton pattern ensures one instance of a class, like `class Singleton { static Singleton& getInstance() { static Singleton instance; return instance; } }`. It uses static for lazy initialization.



137. What is the Factory pattern in C++?


The Factory pattern creates objects via a factory method, like `class Factory { static Shape* create(string type); }`. It decouples object creation, supporting polymorphism.



138. What is the Observer pattern in C++?


The Observer pattern notifies observers of subject changes, like `class Subject { vector observers; void notify(); }`. It’s used for event-driven systems.



139. What is a CRTP in C++?


The Curiously Recurring Template Pattern (CRTP) uses a derived class as a template parameter, like `template class Base {}; class Derived : Base`. It enables static polymorphism.



140. What is SFINAE in C++?


SFINAE (Substitution Failure Is Not An Error) allows template overload resolution to ignore invalid substitutions, like `enable_if`. It’s used for conditional template compilation.



141. What is `std::enable_if` in C++?


`std::enable_if`, introduced in C++11, enables or disables a template based on a condition, like `template, int>



142. What is `std::type_traits` in C++?


`std::type_traits`, introduced in C++11, provides compile-time type information, like `is_integral` or `is_same`. It’s used for template metaprogramming and SFINAE.



143. What is template metaprogramming in C++?


Template metaprogramming uses templates for compile-time computations, like `template struct Factorial { enum { value



144. What is a `volatile` keyword in C++?


`volatile` prevents compiler optimizations for variables that may change unexpectedly, like `volatile int x`. It’s used for hardware registers or multithreaded shared variables.



145. What is the `mutable` keyword in C++?


`mutable` allows a member to be modified in a `const` member function, like `mutable int cache`. It’s used for logical constness, like caching in `const` methods.



146. What is `std::allocator` in C++?


`std::allocator` is a class for managing raw memory allocation, like `allocator alloc`. It’s used by STL containers to customize memory allocation strategies.



147. What is a `std::deque` in C++?


`std::deque` is a double-ended queue, supporting fast insertions at both ends, like `deque d`. It uses multiple fixed-size arrays, balancing `vector` and `list` features.



148. What is a `std::priority_queue` in C++?


`std::priority_queue` is a container adaptor for a max-heap, like `priority_queue pq`. Elements are dequeued in priority order, customizable with a comparator.



149. What is a `std::stack` in C++?


`std::stack` is a container adaptor for LIFO operations, like `stack s`. It uses a `deque` by default, supporting `push()`, `pop()`, and `top()`.



150. What is a `std::queue` in C++?


`std::queue` is a container adaptor for FIFO operations, like `queue q`. It uses a `deque` by default, supporting `push()`, `pop()`, and `front()`.







151. What is the difference between `std::vector`, `std::list`, and `std::deque`?


`std::vector` offers fast random access but slow mid-insertions, `std::list` excels at insertions but lacks random access, and `std::deque` balances both with fast end operations.



152. What is `std::numeric_limits` in C++?


`std::numeric_limits` provides type-specific constants, like `numeric_limits::max()`. It’s used to query properties like minimum, maximum, or infinity for numeric types.



153. What is a `std::complex` in C++?


`std::complex` represents complex numbers, like `complex c(3.0, 4.0)`. It supports arithmetic operations and functions like `abs()` or `conj()`.



154. What is `std::random` in C++?


`std::random`, introduced in C++11, provides random number generation, like `mt19937 rng` and `uniform_int_distribution`. It’s more robust than `rand()`, with better distributions.



155. What is a `std::stringstream` in C++?


`std::stringstream` enables string-based I/O, like `stringstream ss; ss << 123;`. It’s used for parsing or formatting data, combining `string` and stream operations.



156. What is the `std::ios_base` in C++?


`std::ios_base` is the base class for I/O stream classes, managing formatting flags, like `ios_base::hex`. It’s used to control stream behavior, like precision or width.



157. What is a `std::fstream` in C++?


`std::fstream` handles file I/O, supporting both reading and writing, like `fstream file(\"data.txt\")`. It’s used for file operations, ensuring RAII-based resource management.



158. What is a `std::cout` in C++?


`std::cout` is the standard output stream object, like `cout << \"Hello\"`. It’s used for console output, supporting formatting via manipulators like `std::setw`.



159. What is a `std::cin` in C++?


`std::cin` is the standard input stream object, like `int x; cin >> x`. It’s used for console input, handling various data types with error checking.



160. What is `std::endl` in C++?


`std::endl` outputs a newline and flushes the stream, like `cout << \"Hello\" << endl`. It ensures immediate output but can impact performance if overused.



161. What is a `std::setw` in C++?


`std::setw`, from ``, sets the field width for output, like `cout << setw(10) << 123`. It aligns text in formatted output, like tables.



162. What is the difference between `` and ``?


`` provides C++ stream-based I/O (`cout`, `cin`), while `` offers C-style I/O (`printf`, `scanf`). `` is type-safe and extensible, preferred in C++.



163. What is a `std::exception_ptr` in C++?


`std::exception_ptr`, introduced in C++11, captures an exception for later rethrowing, like `exception_ptr ep



164. What is `std::nested_exception` in C++?


`std::nested_exception`, introduced in C++11, captures and nests exceptions, like `throw_with_nested(MyError())`. It’s used to preserve exception context in complex scenarios.



165. What is a `std::source_location` in C++?


`std::source_location`, introduced in C++20, provides compile-time source information, like `source_location::current()`. It’s used for logging file, line, or function names.



166. What is a `std::span` in C++?


`std::span`, introduced in C++20, is a non-owning view over a contiguous sequence, like `span s(arr, size)`. It’s used for safe, bounds-checked array access.



167. What is a `std::bit_cast` in C++?


`std::bit_cast`, introduced in C++20, reinterprets an object’s bits as another type, like `bit_cast(uint32_t)`. It’s safer than `reinterpret_cast`, ensuring size and triviality.



168. What is a `std::jthread` in C++?


`std::jthread`, introduced in C++20, is a thread that auto-joins on destruction, like `jthread t(func)`. It simplifies thread management compared to `std::thread`.



169. What is a `std::latch` in C++?


`std::latch`, introduced in C++20, is a single-use synchronization barrier, like `latch l(3)`. Threads call `count_down()` until it’s ready, used for one-time coordination.



170. What is a `std::barrier` in C++?


`std::barrier`, introduced in C++20, is a reusable synchronization point, like `barrier b(3)`. Threads wait at `arrive_and_wait()`, coordinating iterative tasks.



171. What is a `std::semaphore` in C++?


`std::semaphore`, introduced in C++20, controls resource access, like `counting_semaphore<10> sem(5)`. It’s used for limiting concurrent access, like thread pools.



172. What is a `std::stop_token` in C++?


`std::stop_token`, introduced in C++20, enables cooperative cancellation, like `jthread`’s stop token. Threads check `stop_requested()` to exit gracefully.



173. What is a `std::coroutine` in C++?


`std::coroutine`, introduced in C++20, supports resumable functions, like `generator`. It’s used for asynchronous or lazy evaluation, requiring keywords like `co_yield`.



174. What is `co_await` in C++?


`co_await`, introduced in C++20, suspends a coroutine until a result is ready, like `co_await async_op()`. It’s used in asynchronous programming for non-blocking operations.



175. What is `co_yield` in C++?


`co_yield`, introduced in C++20, yields a value from a coroutine, like `co_yield 5` in a generator. It enables lazy sequence generation, resuming on demand.







176. What is `co_return` in C++?


`co_return`, introduced in C++20, specifies a coroutine’s return value, like `co_return 42`. It completes the coroutine, passing the result to the caller.



177. What is the `boost` library in C++?


Boost is a collection of portable C++ libraries, like `boost::asio` for networking or `boost::shared_ptr`. It extends STL, often influencing C++ standards.



178. What is a unit test in C++?


A unit test verifies a small code unit, like a function, using frameworks like Google Test. It ensures correctness, like `TEST(MyTest, Add) { ASSERT_EQ(3, add(1, 2)); }`.



179. What is Google Test in C++?


Google Test is a C++ testing framework for unit tests, supporting assertions like `ASSERT_EQ` and test fixtures. It’s widely used for reliable, automated testing.



180. What is a mock object in C++?


A mock object simulates a dependency’s behavior, like using Google Mock’s `MOCK_METHOD`. It’s used in unit tests to isolate and verify interactions.



181. What is the difference between `++i` and `i++` in C++?


`++i` (pre-increment) increments `i` and returns the new value, while `i++` (post-increment) increments but returns the old value. Pre-increment is often more efficient.



182. What is the `sizeof` operator in C++?


`sizeof` returns the size of a type or variable in bytes, like `sizeof(int)`. It’s evaluated at compile-time, useful for memory management or serialization.



183. What is a `union` in C++?


A `union` stores different types in the same memory location, like `union Data { int i; float f; }`. Only one member is active, saving space but requiring careful use.



184. What is a `bitfield` in C++?


A bitfield specifies the number of bits for a member, like `struct Flags { unsigned x : 2; }`. It’s used for compact storage, like flags or hardware registers.



185. What is a `volatile` qualifier in C++?


`volatile` prevents compiler optimizations for variables that may change externally, like `volatile int status`. It’s used in embedded systems or multithreading.



186. What is a `thread_local` in C++?


`thread_local`, introduced in C++11, gives each thread its own variable instance, like `thread_local int x`. It’s initialized per-thread, used for thread-specific data.



187. What is a `std::ratio` in C++?


`std::ratio`, introduced in C++11, represents rational numbers at compile-time, like `ratio<1, 3>`. It’s used in `chrono` for time units, like milliseconds.



188. What is a `std::invoke` in C++?


`std::invoke`, introduced in C++17, calls a callable with arguments, like `invoke(func, args...)`. It unifies function pointers, lambdas, and member functions for generic code.



189. What is a `std::apply` in C++?


`std::apply`, introduced in C++17, calls a function with tuple arguments, like `apply(func, tuple{1, 2})`. It’s used to unpack tuples for function invocation.



190. What is a `std::launder` in C++?


`std::launder`, introduced in C++17, ensures pointer validity after placement new, like `launder(ptr)`. It’s used for low-level memory reuse, addressing strict aliasing.



191. What is a `std::byte` in C++?


`std::byte`, introduced in C++17, represents raw bytes, like `byte b{0xFF}`. It’s used for memory manipulation, providing type safety over `char` or `unsigned char`.



192. What is a `std::string_view` in C++?


`std::string_view`, introduced in C++17, is a non-owning view of a string, like `string_view sv



193. What is a `std::concepts` in C++?


`std::concepts`, introduced in C++20, defines requirements for template parameters, like `concept Integral



194. What is a `requires` clause in C++?


A `requires` clause, introduced in C++20, constrains templates with conditions, like `template requires Integral`. It enforces concept-based requirements at compile-time.



195. What is a `std::ranges` in C++?


`std::ranges`, introduced in C++20, enhances STL algorithms with range-based interfaces, like `ranges::sort(v)`. It simplifies code and supports projections and views.



196. What is a `std::view` in C++?


`std::view`, introduced in C++20, represents lazy-evaluated ranges, like `ranges::views::filter`. It’s used for efficient, non-owning transformations, like filtering or mapping.



197. What is a `std::format` in C++?


`std::format`, introduced in C++20, provides Python-like string formatting, like `format(\"Value: {}\", 42)`. It’s type-safe and extensible, replacing `sprintf`.



198. What is a `std::to_chars` in C++?


`std::to_chars`, introduced in C++17, converts numbers to strings, like `to_chars(buffer, buffer + 10, 123)`. It’s low-level, fast, and used for custom formatting.



199. What is a `std::execution` in C++?


`std::execution`, introduced in C++17, specifies parallel execution policies, like `execution::par` for `for_each`. It enables parallel STL algorithms on multi-core systems.



200. What is a `std::memory_order` in C++?


`std::memory_order`, introduced in C++11, controls memory access ordering in atomics, like `memory_order_relaxed`. It’s used for fine-tuned synchronization in multithreading.







201. What is a `std::aligned_storage` in C++?


`std::aligned_storage`, introduced in C++11, provides aligned memory for types, like `aligned_storage`. It’s used for custom memory layouts or placement new.



202. What is a `std::addressof` in C++?


`std::addressof`, introduced in C++11, gets a variable’s address, like `addressof(obj)`, bypassing overloaded `operator&`. It’s used for robust pointer operations.



203. What is a `std::declval` in C++?


`std::declval`, introduced in C++11, creates a dummy object for type deduction, like `decltype(declval().func())`. It’s used in template metaprogramming without instantiation.



204. What is a `std::hash` in C++?


`std::hash` provides a hash function for types, like `hash{}(\"key\")`. It’s used in `unordered_map` or `unordered_set` for key hashing.



205. What is a `std::numeric` in C++?


`std::numeric` provides numerical algorithms, like `accumulate` or `gcd`, introduced in C++17. It’s used for precise computations, like `gcd(48, 18)`.



206. What is a `std::scoped_lock` in C++?


`std::scoped_lock`, introduced in C++17, locks multiple mutexes with deadlock avoidance, like `scoped_lock l(m1, m2)`. It’s an RAII wrapper, simpler than `lock_guard`.



207. What is a `std::shared_mutex` in C++?


`std::shared_mutex`, introduced in C++17, supports shared and exclusive locking, like `shared_lock`. It’s used for read-heavy concurrent access patterns.



208. What is a `std::call_once` in C++?


`std::call_once`, introduced in C++11, ensures a function runs once across threads, like `call_once(flag, func)`. It’s used for thread-safe initialization.



209. What is a `std::packaged_task` in C++?


`std::packaged_task`, introduced in C++11, wraps a callable with a `future`, like `packaged_task pt(func)`. It’s used for asynchronous task execution.



210. What is a `std::error_code` in C++?


`std::error_code`, introduced in C++11, represents platform-specific errors, like `error_code ec`. It’s used in `filesystem` or `asio` for portable error handling.



211. What is a `std::monostate` in C++?


`std::monostate`, introduced in C++17, is a unit type for `variant`, like `variant`. It represents an empty state, useful for default variants.



212. What is a `std::bad_cast` in C++?


`std::bad_cast` is thrown by `dynamic_cast` or `typeid` when a cast fails, like `dynamic_cast(base)`. It indicates a runtime type mismatch.



213. What is a `std::bad_alloc` in C++?


`std::bad_alloc` is thrown by `new` when memory allocation fails, like `new int[large_size]`. It’s caught to handle out-of-memory conditions gracefully.



214. What is a `std::out_of_range` in C++?


`std::out_of_range` is thrown by STL containers, like `vector::at(10)` for invalid indices. It’s used for bounds-checked access, indicating range errors.



215. What is a `std::logic_error` in C++?


`std::logic_error` is a base class for exceptions from logical errors, like `invalid_argument`. It’s used for programmer mistakes, detectable before runtime.



216. What is a `std::runtime_error` in C++?


`std::runtime_error` is a base class for exceptions from runtime issues, like `overflow_error`. It’s used for errors only detectable during execution.



217. What is a `std::filesystem::path` in C++?


`std::filesystem::path` represents a file system path, like `path p



218. What is a `std::chrono::duration` in C++?


`std::chrono::duration` represents a time interval, like `chrono::milliseconds(100)`. It’s used in `chrono` for timing operations, supporting arithmetic and conversions.



219. What is a `std::chrono::time_point` in C++?


`std::chrono::time_point` represents a specific time, like `system_clock::now()`. It’s used in `chrono` for timestamp operations, like calculating time differences.



220. What is a `std::lock` in C++?


`std::lock`, introduced in C++11, locks multiple mutexes without deadlock, like `lock(m1, m2)`. It’s used with `adopt_lock` for safe multi-mutex operations.



221. What is a `std::try_lock` in C++?


`std::try_lock`, introduced in C++11, attempts to lock multiple mutexes, returning -1 on success or the index of the failed mutex. It’s used for non-blocking locking.



222. What is a `std::once_flag` in C++?


`std::once_flag`, introduced in C++11, is a flag for `call_once`, ensuring a function runs once, like `once_flag flag`. It’s thread-safe for initialization.



223. What is a `std::condition_variable_any` in C++?


`std::condition_variable_any`, introduced in C++11, works with any lockable type, unlike `condition_variable`. It’s used for flexible thread synchronization.



224. What is a `std::exchange` in C++?


`std::exchange`, introduced in C++14, replaces a value and returns the old one, like `exchange(x, 5)`. It’s used for atomic updates or move operations.



225. What is a `std::invoke_result` in C++?


`std::invoke_result`, introduced in C++17, deduces a callable’s return type, like `invoke_result_t`. It’s used in template metaprogramming.







226. What is a `std::is_invocable` in C++?


`std::is_invocable`, introduced in C++17, checks if a callable can be invoked with arguments, like `is_invocable_v`. It’s used for type constraints.



227. What is a `std::void_t` in C++?


`std::void_t`, introduced in C++17, maps types to `void`, like `template using void_t



228. What is a `std::common_type` in C++?


`std::common_type`, introduced in C++11, determines a common type for multiple types, like `common_type_t`. It’s used in templates for type deduction.



229. What is a `std::decay` in C++?


`std::decay`, introduced in C++11, applies type transformations, like removing references or `const`, like `decay_t`. It’s used in templates for canonical types.



230. What is a `std::aligned_union` in C++?


`std::aligned_union`, introduced in C++11, provides storage for a union of types with proper alignment, like `aligned_union`. It’s used for type-safe unions.



231. What is a `std::make_signed` in C++?


`std::make_signed`, introduced in C++11, converts a type to its signed equivalent, like `make_signed_t`. It’s used for type manipulation in templates.



232. What is a `std::make_unsigned` in C++?


`std::make_unsigned`, introduced in C++11, converts a type to its unsigned equivalent, like `make_unsigned_t`. It’s used for type transformations in generic code.



233. What is a `std::remove_reference` in C++?


`std::remove_reference`, introduced in C++11, strips reference qualifiers, like `remove_reference_t`. It’s used in templates to normalize types for consistency.



234. What is a `std::remove_const` in C++?


`std::remove_const`, introduced in C++11, removes `const` qualifiers, like `remove_const_t`. It’s used in templates for type manipulation.



235. What is a `std::add_pointer` in C++?


`std::add_pointer`, introduced in C++11, adds a pointer to a type, like `add_pointer_t`. It’s used in template metaprogramming for pointer-based operations.



236. What is a `std::is_same` in C++?


`std::is_same`, introduced in C++11, checks if two types are identical, like `is_same_v`. It’s used in templates for type-based decisions.



237. What is a `std::is_base_of` in C++?


`std::is_base_of`, introduced in C++11, checks if a class is a base of another, like `is_base_of_v`. It’s used for inheritance-based template constraints.



238. What is a `std::is_convertible` in C++?


`std::is_convertible`, introduced in C++11, checks if a type can be converted to another, like `is_convertible_v`. It’s used for type safety in templates.



239. What is a `std::is_trivially_copyable` in C++?


`std::is_trivially_copyable`, introduced in C++11, checks if a type can be copied with `memcpy`, like `is_trivially_copyable_v`. It’s used for optimization or serialization.



240. What is a `std::is_standard_layout` in C++?


`std::is_standard_layout`, introduced in C++11, checks if a type has a standard memory layout, like `is_standard_layout_v`. It’s used for C compatibility or serialization.



241. What is a `std::is_empty` in C++?


`std::is_empty`, introduced in C++11, checks if a class has no data members, like `is_empty_v`. It’s used for optimizations like empty base optimization.



242. What is a `std::is_polymorphic` in C++?


`std::is_polymorphic`, introduced in C++11, checks if a class has virtual functions, like `is_polymorphic_v`. It’s used for RTTI or dynamic_cast checks.



243. What is a `std::is_final` in C++?


`std::is_final`, introduced in C++14, checks if a class or function is marked `final`, like `is_final_v`. It’s used for template constraints.



244. What is a `std::is_aggregate` in C++?


`std::is_aggregate`, introduced in C++17, checks if a class is an aggregate, like `is_aggregate_v`. It’s used for structured bindings or initialization.



245. What is a `std::has_unique_object_representations` in C++?


`std::has_unique_object_representations`, introduced in C++17, checks if a type’s objects have unique memory representations, like `has_unique_object_representations_v`. It’s used for serialization.



246. What is a `std::integer_sequence` in C++?


`std::integer_sequence`, introduced in C++14, represents a compile-time sequence of integers, like `integer_sequence`. It’s used in template metaprogramming for indexing.



247. What is a `std::index_sequence` in C++?


`std::index_sequence`, introduced in C++14, is an `integer_sequence` for indices, like `index_sequence<0, 1, 2>`. It’s used for tuple unpacking or variadic templates.



248. What is a `std::make_index_sequence` in C++?


`std::make_index_sequence`, introduced in C++14, generates an `index_sequence`, like `make_index_sequence<3>`. It’s used in templates for compile-time index generation.



249. What is a `std::tuple_size` in C++?


`std::tuple_size`, introduced in C++11, gives the number of elements in a tuple, like `tuple_size_v>`. It’s used for generic tuple manipulation.



250. What is a `std::tuple_element` in C++?


`std::tuple_element`, introduced in C++11, gets the type of a tuple’s element, like `tuple_element_t<0, tuple>`. It’s used for accessing tuple types.







251. What is a `std::apply` in C++?


`std::apply`, introduced in C++17, invokes a callable with tuple arguments, like `apply(func, tuple{1, 2})`. It simplifies tuple unpacking for function calls.



252. What is a `std::make_from_tuple` in C++?


`std::make_from_tuple`, introduced in C++17, constructs an object from tuple arguments, like `make_from_tuple(tuple{1, 2})`. It’s used for generic object creation.



253. What is a `std::experimental` namespace in C++?


`std::experimental` contains proposed features, like `optional` before C++17. It’s a testing ground for future standard library additions, not guaranteed to be stable.



254. What is a `std::pmr` in C++?


`std::pmr`, introduced in C++17, is the polymorphic memory resource namespace, like `pmr::polymorphic_allocator`. It’s used for customizable memory allocation in containers.



255. What is a `std::memory_resource` in C++?


`std::memory_resource`, introduced in C++17, is an abstract base for memory allocators, like `pmr::new_delete_resource`. It’s used for flexible memory management in `pmr` containers.



256. What is a `std::pmr::vector` in C++?


`std::pmr::vector`, introduced in C++17, is a `vector` using a polymorphic allocator, like `pmr::vector v`. It supports custom memory resources for allocation.



257. What is a `std::scoped_allocator_adaptor` in C++?


`std::scoped_allocator_adaptor`, introduced in C++11, propagates allocators to nested containers, like `vector>`. It ensures consistent allocation.



258. What is a `std::uses_allocator` in C++?


`std::uses_allocator`, introduced in C++11, checks if a type supports an allocator, like `uses_allocator_v, allocator>`. It’s used for allocator-aware containers.



259. What is a `std::allocator_traits` in C++?


`std::allocator_traits`, introduced in C++11, provides a uniform interface for allocators, like `allocator_traits::allocate`. It simplifies allocator usage in generic code.



260. What is a `std::uninitialized_copy` in C++?


`std::uninitialized_copy` copies a range to uninitialized memory, like `uninitialized_copy(begin, end, dest)`. It’s used for efficient container initialization, avoiding default construction.



261. What is a `std::uninitialized_fill` in C++?


`std::uninitialized_fill` fills uninitialized memory with a value, like `uninitialized_fill(begin, end, value)`. It’s used for bulk initialization in custom allocators.



262. What is a `std::destroy` in C++?


`std::destroy`, introduced in C++17, calls destructors on a range, like `destroy(begin, end)`. It’s used in containers for explicit cleanup without deallocation.



263. What is a `std::construct_at` in C++?


`std::construct_at`, introduced in C++20, constructs an object at a specific address, like `construct_at(ptr, args...)`. It’s used for in-place construction in allocators.



264. What is a `std::to_address` in C++?


`std::to_address`, introduced in C++20, converts a pointer-like object to a raw pointer, like `to_address(fancy_ptr)`. It’s used for uniform pointer access.



265. What is a `std::assume_aligned` in C++?


`std::assume_aligned`, introduced in C++20, hints to the compiler about pointer alignment, like `assume_aligned<16>(ptr)`. It optimizes code but requires correct alignment.



266. What is a `std::start_lifetime_as` in C++?


`std::start_lifetime_as`, introduced in C++23, starts an object’s lifetime at a memory location, like `start_lifetime_as(ptr)`. It’s used for safe memory reuse.



267. What is a `std::bit_ceil` in C++?


`std::bit_ceil`, introduced in C++20, returns the smallest power of 2 greater than or equal to a number, like `bit_ceil(5)`. It’s used for memory alignment.



268. What is a `std::popcount` in C++?


`std::popcount`, introduced in C++20, counts the number of set bits, like `popcount(0b1011)`. It’s used for bit manipulation in algorithms or compression.



269. What is a `std::endian` in C++?


`std::endian`, introduced in C++20, checks the platform’s byte order, like `endian::big` or `endian::little`. It’s used for portable serialization or networking.



270. What is a `std::lerp` in C++?


`std::lerp`, introduced in C++20, performs linear interpolation, like `lerp(a, b, t)`. It’s used in graphics or animations for smooth transitions.



271. What is a `std::midpoint` in C++?


`std::midpoint`, introduced in C++20, computes the midpoint of two values, like `midpoint(1, 5)`. It’s safer than `(a + b) / 2`, avoiding overflow.



List Memory Pages
Share Via Whastapp/Facebook
Share to Your Friends

Share this protal to share friends and complete unlimited tests here. You can also make friends on our protal also start mutual competition tests with your firends easily.

Share to Facebook Share to WhatsApp Promote & Earn