C++ Interview Questions and Answers


What is C++?
  • C++ is a general-purpose, object-oriented programming (OOP) language developed by Bjarne Stroustrup as an extension of the C language. It supports multiple programming paradigms, including procedural, object-oriented, and generic programming.
What are the key features of C++?
  • Object-Oriented (Classes, Objects, Inheritance, Polymorphism, Encapsulation, Abstraction).
  • Mid-level language (combines features of low-level and high-level).
  • Rich set of built-in functions and operators.
  • Memory management (both manual with pointers and dynamic allocation with new/delete, and automatic with smart pointers).
  • Standard Template Library (STL).
  • Exception Handling.
  • Operator Overloading.
  • Function Overloading.
  • Templates.
  • Namespaces.
What is the difference between C and C++?
  • C is a procedural language, while C++ is object-oriented (though it supports procedural programming).
  • C does not support classes, objects, inheritance, polymorphism, function overloading, or operator overloading. C++ does.
  • C uses malloc() and free() for dynamic memory allocation. C++ uses new and delete (and smart pointers).
  • C uses stdio.h for input/output (printf, scanf). C++ uses iostream (cout, cin).
  • C does not have built-in exception handling. C++ has try-catch blocks.
  • C++ has namespaces to prevent naming conflicts. C does not.
Explain the compilation process in C++.
  • Similar to C, but includes additional steps to handle C++ features:
    1. Preprocessing: Handles directives like #include and #define.
    2. Compilation: Translates preprocessed code into assembly language.
    3. Assembly: Translates assembly code into machine code (object code).
    4. Linking: Combines object code with necessary libraries and other object files to create an executable.
What is the basic structure of a C++ program?
  • A basic C++ program includes:
    • Preprocessor directives (e.g., #include ).
    • Namespace declarations (e.g., using namespace std;).
    • The main() function.
    • Body of the main() function with statements, variables, and object creations.
    • Class definitions (optional).
    • User-defined function definitions (optional).
What is a class in C++?
  • A class is a blueprint or template for creating objects. It encapsulates data (data members) and the functions that operate on that data (member functions) into a single unit.
What is an object in C++?
  • An object is an instance of a class. It is a concrete entity created based on the class definition, with its own set of data members.
What are access specifiers in C++?
  • Access specifiers control the visibility and accessibility of class members (data members and member functions).
    • public: Members are accessible from anywhere, inside or outside the class.
    • private: Members are accessible only from within the same class.
    • protected: Members are accessible within the same class and by derived classes.
What is encapsulation?
  • Encapsulation is the bundling of data and the methods that operate on that data within a single unit (a class). It also involves data hiding, where the internal representation of an object is hidden from the outside world, and access is provided only through public member functions.
What is abstraction?
  • Abstraction is the process of hiding complex implementation details and showing only the essential features of an object. It focuses on what an object does rather than how it does it. Abstract classes and interfaces are used to achieve abstraction.
What is inheritance?
  • Inheritance is a mechanism that allows a new class (derived class) to inherit properties (data members and member functions) from an existing class (base class). It promotes code reusability and establishes an "is-a" relationship between classes.
What are the different types of inheritance in C++?
  • Single inheritance.
  • Multiple inheritance.
  • Multilevel inheritance.
  • Hierarchical inheritance.
  • Hybrid inheritance (combination of multiple types).
What is polymorphism?
  • Polymorphism means "many forms." In C++, it allows objects of different classes to respond to the same method call in their own specific way. It enables a single interface to be used for a variety of types.
What are the types of polymorphism in C++?
  • Compile-time polymorphism (Static Binding): Achieved through function overloading and operator overloading. The function call is resolved at compile time.
  • Runtime polymorphism (Dynamic Binding): Achieved through virtual functions and pointers/references to base classes. The function call is resolved at runtime.
What is function overloading?
  • Function overloading allows you to define multiple functions with the same name but different parameter lists (different number of parameters, different types of parameters, or both). The compiler determines which function to call based on the arguments passed.
What is operator overloading?
  • Operator overloading allows you to redefine the meaning of C++ operators for user-defined data types (classes). This makes working with objects more intuitive and similar to working with built-in types.
What is a constructor?
  • A constructor is a special member function of a class that is automatically called when an object of that class is created. Its primary purpose is to initialize the data members of the object. It has the same name as the class and no return type.
What is a destructor?
  • A destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted. Its primary purpose is to clean up resources allocated by the object (e.g., dynamically allocated memory). It has the same name as the class prefixed with a tilde (~) and no return type or parameters.
Explain the different types of constructors.
  • Default Constructor: A constructor that takes no arguments. If you don't provide any constructor, the compiler provides a default constructor.
  • Parameterized Constructor: A constructor that takes one or more arguments to initialize the object with specific values.
  • Copy Constructor: A constructor that creates a new object as a copy of an existing object of the same class. It takes a reference to an object of the same class as an argument.
What is the Rule of Three/Five?
  • The Rule of Three states that if a class needs a user-defined destructor, copy constructor, or copy assignment operator, it likely needs all three to manage resources correctly.
  • With the introduction of move semantics in C++11, the rule was extended to the Rule of Five, which includes the move constructor and move assignment operator. If a class needs any of the "big three," it often needs all five to handle resource management efficiently and correctly.
What is a virtual function?
  • A virtual function is a member function in a base class that you declare with the virtual keyword. It allows you to achieve runtime polymorphism. When a virtual function is called through a pointer or reference to a base class, the actual function executed depends on the type of the object being pointed to, not the type of the pointer/reference.
What is an abstract class?
  • An abstract class is a class that cannot be instantiated (you cannot create objects of an abstract class). It is designed to be a base class for other classes. An abstract class typically contains one or more pure virtual functions.
What is a pure virtual function?
  • A pure virtual function is a virtual function declared in a base class with = 0; at the end of its declaration (e.g., virtual void myFunction() = 0;). It has no implementation in the base class. Derived classes must provide an implementation for all pure virtual functions to be concrete (instantiable).
What is the difference between a virtual function and a pure virtual function?
  • A virtual function has an implementation in the base class, and derived classes can optionally override it.
  • A pure virtual function has no implementation in the base class, and derived classes *must* provide an implementation.
What is the purpose of the this pointer?
  • The this pointer is an implicit pointer within a member function that points to the object on which the member function is called. It is used to refer to the current object's data members or member functions, especially when there are name conflicts or when returning the current object.
What is the difference between a pointer and a reference?
  • Pointer: A variable that stores the memory address of another variable. Can be NULL. Can be reassigned to point to a different variable. Requires dereferencing (*) to access the value it points to.
  • Reference: An alias or alternative name for an existing variable. Must be initialized when declared and cannot be reassigned to refer to another variable. Cannot be NULL. Does not require dereferencing; you use the reference name directly.
What is dynamic memory allocation in C++?
  • Dynamic memory allocation is the process of allocating memory during program execution (runtime) from the heap. In C++, this is done using the new operator.
What is the difference between new/delete and malloc/free?
  • new/delete (C++): Operators. new allocates memory and calls the constructor for objects. delete deallocates memory and calls the destructor for objects. Type-safe (returns a typed pointer). Can be overloaded.
  • malloc/free (C): Functions. malloc allocates raw memory (returns void*). free deallocates memory. Do not call constructors or destructors. Not type-safe (requires casting). Cannot be overloaded.
What is a smart pointer?
  • A smart pointer is an object that acts like a pointer but provides automatic memory management. It uses RAII (Resource Acquisition Is Initialization) to ensure that allocated memory is automatically deallocated when the smart pointer goes out of scope, preventing memory leaks.
Explain std::unique_ptr.
  • std::unique_ptr is a smart pointer that owns a dynamically allocated object exclusively. Only one unique_ptr can point to the same object at any given time. It cannot be copied, but it can be moved (transferring ownership).
Explain std::shared_ptr.
  • std::shared_ptr is a smart pointer that allows multiple pointers to share ownership of the same dynamically allocated object. It uses a reference count to track the number of pointers pointing to the object. The object is deallocated when the last shared_ptr pointing to it is destroyed.
Explain std::weak_ptr.
  • std::weak_ptr is a non-owning smart pointer that provides a non-owning reference to an object managed by a std::shared_ptr. It does not affect the reference count. It is used to break circular references between shared_ptrs and to observe an object without extending its lifetime. You need to convert a weak_ptr to a shared_ptr (using lock()) to access the object.
What is the STL (Standard Template Library)?
  • The STL is a set of C++ template classes that provide generic data structures (containers) and algorithms. It's a key part of the C++ standard library and promotes code reusability and efficiency.
What are the main components of the STL?
  • Containers: Data structures (e.g., vector, list, map, set).
  • Algorithms: Functions that perform operations on data in containers (e.g., sort, find, copy).
  • Iterators: Generalize the concept of pointers to traverse elements in containers.
  • Functors (Function Objects): Objects that can be called like functions.
  • Adaptors: Provide a different interface to containers (e.g., stack, queue).
What is a std::vector?
  • std::vector is a sequence container that represents a dynamic array. It can grow or shrink in size as needed. Elements are stored contiguously in memory, allowing for efficient random access.
What is a std::list?
  • std::list is a sequence container that implements a doubly linked list. Elements are not stored contiguously. Insertion and deletion are efficient (constant time), but random access is slow.
What is a std::map?
  • std::map is an associative container that stores key-value pairs. Elements are sorted by key, and keys are unique. It is implemented using a balanced binary search tree.
What is a std::unordered_map?
  • std::unordered_map is an associative container that stores key-value pairs in an unordered manner. It is implemented using a hash table, providing average constant-time complexity for insertion, deletion, and lookup. Keys are unique.
What are iterators in STL?
  • Iterators are objects that provide a way to access elements in containers sequentially, similar to pointers. They abstract the underlying data structure, allowing algorithms to work with different container types.
What is the difference between const and constexpr? (C++11)
  • const: Indicates that a variable's value cannot be changed after initialization. The value can be determined at runtime.
  • constexpr: Indicates that an expression can be evaluated at compile time. Can be applied to variables, functions, and constructors. Guarantees compile-time evaluation if possible, making code potentially faster and enabling its use in contexts that require compile-time constants (like array sizes).
What is a lambda expression? (C++11)
  • A lambda expression (or lambda function) is a concise way to create an anonymous function object. It is often used for short, inline functions, particularly with STL algorithms. Its syntax is [capture_clause](parameters) -> return_type { body }.
What is move semantics? (C++11)
  • Move semantics is a feature that allows resources (like memory or file handles) to be transferred from one object to another efficiently, without performing a deep copy. It is implemented using rvalue references, move constructors, and move assignment operators.
What are rvalue references? (C++11)
  • Rvalue references are a new type of reference in C++ that can bind to rvalues (temporary values or expressions that don't have a persistent memory location). They are denoted by a double ampersand (&&). They are crucial for implementing move semantics.
Explain the difference between Lvalue and Rvalue. (revisited)
  • Lvalue: An expression that refers to a memory location that can be assigned a value (e.g., a variable name). Can appear on the left side of an assignment.
  • Rvalue: An expression that represents a temporary value and does not refer to a persistent memory location that can be assigned to (e.g., a literal, the result of an expression). Can only appear on the right side of an assignment.
What is exception handling in C++?
  • Exception handling is a mechanism to deal with runtime errors or exceptional conditions in a structured way. It involves the try, catch, and throw keywords.
Explain the try, catch, and throw keywords.
  • try: A block of code that might throw an exception.
  • throw: Used to signal that an exceptional condition has occurred. It throws an exception object.
  • catch: A block of code that handles a specific type of exception thrown in the preceding try block.
What is RAII (Resource Acquisition Is Initialization)?
  • RAII is a programming idiom where resource management (like memory allocation, file handles, locks) is tied to the lifetime of objects. Resources are acquired in the constructor and automatically released in the destructor. This guarantees that resources are properly cleaned up, even in the presence of exceptions. Smart pointers are a prime example of RAII.
What is a namespace?
  • A namespace is a declarative region that provides a scope for identifiers (names of variables, functions, classes, etc.). It is used to organize code into logical groups and prevent naming conflicts, especially in large projects or when using multiple libraries.
What is the purpose of using namespace std;?
  • using namespace std; brings all the names from the std namespace into the current scope. This allows you to use elements like cout and cin directly without the std:: prefix. While convenient, it can lead to naming conflicts if other namespaces or global identifiers have the same names. It's often better practice to use the std:: prefix or selectively bring in specific names (e.g., using std::cout;).
What is the difference between struct and class in C++?
  • In C++, the only difference between struct and class is the default access specifier for members:
    • In a struct, members are public by default.
    • In a class, members are private by default.
  • Otherwise, they are functionally equivalent; you can have member functions, constructors, inheritance, etc., in both. Conventionally, struct is often used for plain old data (POD) structures with no member functions, while class is used for more complex objects with member functions and encapsulated data.
What is a friend function and a friend class?
  • A friend function is a function that is not a member of a class but is granted access to the private and protected members of that class. It is declared within the class definition using the friend keyword.
  • A friend class is a class whose member functions are all granted access to the private and protected members of another class.
  • Friend relationships are not reciprocal or transitive.
What is the difference between function overloading and function overriding?
  • Function Overloading: Defining multiple functions with the same name but different parameter lists within the same scope. (Compile-time polymorphism).
  • Function Overriding: Defining a function in a derived class with the same name, return type, and parameter list as a virtual function in its base class. (Runtime polymorphism).
What is a virtual destructor?
  • A virtual destructor is a destructor declared with the virtual keyword in a base class. It is essential when dealing with inheritance and dynamic memory allocation. If you delete a derived class object through a base class pointer, the virtual destructor ensures that the correct derived class destructor is called, followed by the base class destructor, preventing resource leaks.
What is the purpose of static_cast?
  • static_cast is a compile-time cast used for conversions between related types, such as converting a pointer to a base class to a pointer to a derived class (downcasting - unsafe without checking type), converting between numeric types, or converting between pointers to void and pointers to other types. It performs checks at compile time but not at runtime.
What is the purpose of dynamic_cast?
  • dynamic_cast is a runtime cast used for safe downcasting in an inheritance hierarchy. It is used with pointers or references to polymorphic types (classes with at least one virtual function). It checks at runtime whether the cast is valid. If the cast fails for pointers, it returns nullptr; if it fails for references, it throws a std::bad_cast exception.
What is the purpose of const_cast?
  • const_cast is used to add or remove the const or volatile qualifier from a variable or pointer. It is typically used when you need to pass a const object to a function that expects a non-const argument (and you know the function won't actually modify the object). Using const_cast to modify a variable that was originally declared as const is undefined behavior.
What is the purpose of reinterpret_cast?
  • reinterpret_cast is a low-level cast that performs a bitwise reinterpretation of the operand's value. It can convert any pointer type to any other pointer type, any integer type to any pointer type, and vice versa. It is the most dangerous cast and should be used with extreme caution as it can easily lead to undefined behavior.
What is the difference between shallow copy and deep copy?
  • Shallow Copy: Creates a new object and copies the values of the data members from the original object. If the object contains pointers to dynamically allocated memory, only the pointer itself is copied, not the data it points to. This can lead to multiple objects pointing to the same memory, causing issues when one object's destructor tries to deallocate the memory.
  • Deep Copy: Creates a new object and copies the values of the data members. If the object contains pointers to dynamically allocated memory, a new block of memory is allocated, and the *contents* of the original memory are copied to the new block. Each object has its own independent copy of the data. This is typically needed when a class manages resources like dynamic memory.
When is a copy constructor called?
  • A copy constructor is called in the following situations:
    • When an object is initialized with another object of the same class (e.g., MyClass obj2 = obj1; or MyClass obj2(obj1);).
    • When an object is passed by value to a function.
    • When an object is returned by value from a function.
What is the copy assignment operator?
  • The copy assignment operator (operator=) is a member function that is called when an existing object is assigned the value of another existing object of the same class (e.g., obj2 = obj1;). It is responsible for properly copying data and handling resource management (like deallocating existing resources before copying).
What is the difference between a copy constructor and the copy assignment operator?
  • The copy constructor is called when a *new* object is created and initialized with an existing object.
  • The copy assignment operator is called when an *existing* object is assigned the value of another existing object.
What is the purpose of std::move? (C++11)
  • std::move is a utility function that converts an Lvalue into an Rvalue reference. It doesn't actually move anything; it simply signals the compiler that the object can be "moved from" (its resources can be transferred to another object). This enables the compiler to select the move constructor or move assignment operator if available, leading to efficient resource transfer instead of a deep copy.
What is the purpose of std::forward? (C++11)
  • std::forward is a utility function used in template programming, particularly with perfect forwarding. It conditionally casts its argument to an rvalue reference based on whether the original argument was an rvalue. This allows a template function to forward its arguments to another function while preserving their original value category (Lvalue or Rvalue).
What is a template?
  • A template is a blueprint or formula for creating a generic class or function. It allows you to write code that can work with different data types without having to rewrite the code for each type. Templates are a form of generic programming.
What is the difference between function templates and class templates?
  • Function Template: A template used to create a family of functions that perform the same operation on different data types (e.g., a generic swap function).
  • Class Template: A template used to create a family of classes that have the same structure and behavior but operate on different data types (e.g., a generic Stack or List class).
What is template specialization?
  • Template specialization allows you to provide a specific implementation for a template when it is instantiated with a particular data type. This is useful when the generic template implementation is not optimal or correct for a specific type.
What is file handling in C++?
  • File handling in C++ involves using the fstream library to perform operations on files, such as reading from and writing to files.
What are the classes used for file handling in C++?
  • std::ifstream: For input operations on files.
  • std::ofstream: For output operations on files.
  • std::fstream: For both input and output operations on files.
What is the difference between text mode and binary mode in file handling?
  • Text mode: Data is treated as characters, and newline characters may be translated between platform-specific representations.
  • Binary mode: Data is treated as raw bytes without any translation. Used for non-text data.
What is the purpose of std::endl?
  • std::endl is a manipulator used with output streams (like std::cout). It inserts a newline character and flushes the output buffer. Flushing ensures that the output is immediately displayed on the console.
What is the difference between '\n' and std::endl?
  • '\n' is a newline character. It simply moves the cursor to the next line.
  • std::endl inserts a newline character and also flushes the output buffer. Flushing can be a performance overhead if done excessively. For just a newline, '\n' is generally preferred unless you specifically need to flush the buffer.
What is the purpose of std::cin.ignore()?
  • std::cin.ignore() is used to discard characters from the input buffer. It's often used after reading formatted input (like numbers) to clear the remaining characters, including the newline character, before reading a line of text with std::getline() or std::cin again.
What is the difference between std::cin >> var; and std::getline(std::cin, str);?
  • std::cin >> var;: Reads input based on the type of var. For strings, it reads a sequence of non-whitespace characters and stops at the first whitespace.
  • std::getline(std::cin, str);: Reads an entire line of input from the stream, including whitespace, until a newline character is encountered (which is then discarded). It is generally safer for reading lines of text.
What is the purpose of the explicit keyword?
  • The explicit keyword is used with constructors to prevent implicit type conversions. A constructor declared with explicit can only be used for direct initialization, not for implicit conversions. This helps prevent unexpected type conversions and potential bugs.
What is the purpose of the mutable keyword?
  • The mutable keyword is used with class data members. A mutable data member can be modified even if it is part of a const object or accessed through a const member function. It is typically used for members that are used for caching or synchronization and do not affect the observable state of the object.
What is a forwarding reference (Universal Reference)? (C++11)
  • Forwarding references (originally called universal references) are a special type of reference (T&&) that can bind to both Lvalues and Rvalues depending on the context of template argument deduction. They are used in template functions to preserve the original value category of the argument when perfect forwarding.
What is perfect forwarding? (C++11)
  • Perfect forwarding is the ability to pass arguments of a function template to another function while preserving their original value categories (Lvalue or Rvalue) and const/volatile qualifiers. It is typically achieved using forwarding references and std::forward.
What is the purpose of the noexcept specifier? (C++11)
  • The noexcept specifier indicates that a function does not throw any exceptions. If a function declared with noexcept throws an exception, the program will terminate immediately (by calling std::terminate). It helps the compiler optimize code and provides information to the caller about the function's exception behavior.
What is the difference between const char *p = "hello"; and char p[] = "hello"; in C++? (revisited)
  • const char *p = "hello";: p is a pointer to the first character of a string literal. String literals are constant in C++, so you cannot modify the characters through p. p can be made to point to another memory location.
  • char p[] = "hello";: p is a character array initialized with the string literal. The array is in writable memory, and its contents can be modified. p is the array name, which is a constant pointer to the first element.
What is the purpose of the auto keyword? (C++11)
  • The auto keyword allows the compiler to deduce the type of a variable from its initializer. It simplifies code when dealing with complex types, especially with iterators and lambda expressions.
What is the purpose of the range-based for loop? (C++11)
  • The range-based for loop provides a simpler syntax for iterating over elements in a range (like arrays, containers, or anything that supports iterators). Its syntax is for (declaration : range) { body }.
What is initializer list? (C++11)
  • An initializer list (std::initializer_list) is a lightweight proxy object that provides access to a list of objects of type T. It is typically used to initialize containers or pass a variable number of arguments to functions.
What is the purpose of the nullptr keyword? (C++11)
  • nullptr is a keyword that represents a null pointer constant. It is a distinct type (std::nullptr_t) and is preferred over NULL or 0 for representing null pointers, as it helps avoid ambiguity in function overloads and improves type safety.
What is the difference between NULL, 0, and nullptr?
  • NULL: A macro often defined as 0 or (void*)0. Can be ambiguous with integer 0.
  • 0: An integer literal. Can be implicitly converted to a null pointer, but can also be an integer value, leading to ambiguity.
  • nullptr: A distinct keyword representing a null pointer constant with its own type. Preferred for representing null pointers in modern C++.
What is the purpose of the delete keyword in function declarations? (C++11)
  • The = delete; syntax after a function declaration explicitly deletes the function, preventing its use. This is often used to disable implicitly generated member functions (like the copy constructor or assignment operator) or to prevent the use of certain function overloads.
What is the purpose of the default keyword in function declarations? (C++11)
  • The = default; syntax after a function declaration explicitly tells the compiler to generate the default implementation for a special member function (like the default constructor, copy constructor, assignment operator, destructor, move constructor, or move assignment operator). This is useful when you want to provide some custom behavior but still use the compiler's default implementation for certain members.
What is perfect forwarding? (revisited)
  • Perfect forwarding is the ability to pass arguments through a template function to another function without losing their original value category (Lvalue or Rvalue) or const/volatile qualifiers. It is typically achieved using forwarding references (T&&) and std::forward.
What is the concept of SFINAE (Substitution Failure Is Not An Error)?
  • SFINAE is a rule in C++ template metaprogramming that applies when the compiler is deducing template arguments for a function template. If substituting the template arguments into the function's signature results in an invalid type or expression, it's not treated as a compilation error but rather as a failure to generate a valid function signature. The compiler then moves on to consider other function overloads or template specializations.
What is the purpose of the decltype specifier? (C++11)
  • The decltype specifier yields the declared type of an entity or the type of an expression. It is useful for determining the type of a variable or the return type of a function based on an expression, particularly in generic programming.
What is the difference between auto and decltype?
  • auto: Deduces the type of a variable from its initializer. It often strips references and top-level const/volatile qualifiers.
  • decltype: Yields the exact declared type of an entity or the precise type of an expression, including references and const/volatile qualifiers.
What is the purpose of the final specifier? (C++11)
  • The final specifier can be applied to a class or a virtual function.
    • Applied to a class: Prevents the class from being inherited from.
    • Applied to a virtual function: Prevents derived classes from overriding that virtual function.
What is the purpose of the override specifier? (C++11)
  • The override specifier is used with member functions in derived classes to explicitly indicate that the function is intended to override a virtual function in the base class. If the function signature does not match a virtual function in the base class, the compiler will issue an error, helping to prevent accidental mistakes.
What is a thread in C++? (C++11)
  • A thread is a single sequence of execution within a program. Multithreading allows a program to perform multiple tasks concurrently by running multiple threads simultaneously. C++11 introduced built-in support for multithreading through the header.
What is a mutex? (C++11)
  • A mutex (mutual exclusion) is a synchronization primitive used to protect shared resources from concurrent access by multiple threads. It ensures that only one thread can access the protected resource at a time, preventing race conditions.
What is a lock guard? (C++11)
  • std::lock_guard is a simple RAII wrapper around a mutex. It automatically locks the mutex when the lock_guard object is created and unlocks the mutex when the lock_guard goes out of scope (due to normal execution or an exception). This simplifies mutex management and helps prevent deadlocks due to forgotten unlocks.
What is a unique lock? (C++11)
  • std::unique_lock is a more flexible RAII wrapper around a mutex compared to std::lock_guard. It allows for deferred locking, timed locking, and transferring ownership of the lock.
What is a condition variable? (C++11)
  • A condition variable is a synchronization primitive that allows threads to wait for a certain condition to become true. Threads can block on a condition variable, releasing a mutex, and be woken up by another thread that signals the condition has changed.
What are atomic operations? (C++11)
  • Atomic operations are operations that are guaranteed to complete without interruption from other threads. They are used for low-level synchronization and to avoid race conditions on simple data types without using mutexes. C++11 provides the header for atomic types and operations.
What are futures and promises? (C++11)
  • Futures and promises are used for asynchronous programming and communicating results between threads.
    • A std::promise is used by one thread to set a value or an exception.
    • A std::future is used by another thread to retrieve the value or exception set by the promise. The thread can wait for the result to become available.
What is the difference between std::vector v; and std::list l;? (revisited)
  • std::vector: Dynamic array, contiguous memory, efficient random access, less efficient insertion/deletion in the middle.
  • std::list: Doubly linked list, non-contiguous memory, efficient insertion/deletion anywhere, inefficient random access.
What is the difference between std::set s; and std::unordered_set us;? (revisited)
  • std::set: Stores unique elements in sorted order, implemented using a balanced binary search tree (typically red-black tree), logarithmic time complexity for operations.
  • std::unordered_set: Stores unique elements in an unordered manner, implemented using a hash table, average constant-time complexity for operations (worst-case linear).
What is the purpose of const member functions?
  • A const member function is a member function declared with the const keyword after the parameter list (e.g., void myFunction() const;). It guarantees that the function will not modify the object's data members. You can call const member functions on const objects.
Can a const member function modify a data member?
  • Normally, no. However, a const member function *can* modify a data member that is declared as mutable.
What is the purpose of static data members?
  • A static data member belongs to the class itself, not to individual objects of the class. There is only one copy of a static data member shared by all objects of the class. It must be defined and initialized outside the class definition.
What is the purpose of static member functions?
  • A static member function also belongs to the class and can be called using the class name (e.g., ClassName::staticFunction();) or through an object. It can only access static data members and static member functions of the same class. It does not have a this pointer.
What is the difference between a member function and a non-member function?
  • Member function: A function that is part of a class. It operates on objects of that class and has access to the object's data members (including private and protected).
  • Non-member function: A function that is not part of any class. It cannot directly access the private or protected members of a class unless it is declared as a friend of that class.
What is the purpose of the inline keyword?
  • The inline keyword is a hint to the compiler to replace the function call with the function's body directly at the call site. This can potentially improve performance by avoiding function call overhead, but it can also increase code size. The compiler may ignore the inline hint.
What is the difference between a macro and an inline function? (revisited)
  • Macro: Text substitution by the preprocessor. No type checking, potential side effects with arguments, increases code size, difficult to debug.
  • Inline function: Processed by the compiler. Type-checked, avoids side effects, compiler can decide whether to inline or not, debuggable. Generally preferred over macros for performance-critical small functions.
What is the difference between a reference and a pointer? (revisited)
  • Reference: Alias, must be initialized, cannot be null, cannot be reseated, no separate memory for the reference itself (conceptually), no dereferencing needed.
  • Pointer: Stores address, can be null, can be reseated, has its own memory, requires dereferencing (*) to access the value.
What is the purpose of the using declaration? (C++11)
  • The using declaration (e.g., using std::cout;) brings a specific name from a namespace into the current scope. It's a more targeted way to access members of a namespace compared to using namespace std;.
What is the purpose of the using alias declaration? (C++11)
  • The using alias declaration (e.g., using VectorInt = std::vector;) creates an alias for an existing type. It is a more flexible and powerful alternative to typedef, especially with templates.
What is the difference between typedef and using alias declaration?
  • typedef: Creates an alias for an existing type. Cannot be used with template parameters in a way that allows partial specialization.
  • using alias declaration: Creates an alias for an existing type. More flexible, can be used with template parameters to create alias templates.
What is the purpose of the alignas specifier? (C++11)
  • The alignas specifier is used to specify the alignment requirement of an object or a type. It ensures that the memory address of the object is a multiple of the specified alignment value. This can be important for performance and hardware interactions.
What is the purpose of the alignof operator? (C++11)
  • The alignof operator returns the alignment requirement of a type.
What is a move constructor? (C++11)
  • A move constructor is a special member function that efficiently transfers resources from a temporary object (an rvalue) to a new object. It takes an rvalue reference to an object of the same class as an argument. It is typically faster than a copy constructor because it avoids deep copying.
What is a move assignment operator? (C++11)
  • The move assignment operator (operator= with an rvalue reference parameter) efficiently transfers resources from a temporary object (an rvalue) to an existing object. It is similar to the move constructor but is used for assignment.
When are move constructor and move assignment operator implicitly generated by the compiler?
  • The compiler implicitly generates a move constructor and a move assignment operator if you have not declared any of the following:
    • Copy constructor.
    • Copy assignment operator.
    • Destructor.
    • Explicitly deleted move constructor or move assignment operator.
What is the purpose of the [[nodiscard]] attribute? (C++17)
  • The [[nodiscard]] attribute is used to indicate that the return value of a function should not be ignored. If the caller discards the return value, the compiler will issue a warning. This is useful for functions whose return value indicates success/failure or holds a resource that needs to be managed.
What is the purpose of the [[maybe_unused]] attribute? (C++17)
  • The [[maybe_unused]] attribute is used to suppress compiler warnings about unused variables, parameters, functions, or enumerators. It indicates that the entity might be intentionally unused in some contexts.
What is the purpose of the [[fallthrough]] attribute? (C++17)
  • The [[fallthrough]] attribute is used within a switch statement to indicate that control is intended to fall through from one case label to the next. It suppresses compiler warnings about implicit fallthrough.
What is a structured binding? (C++17)
  • Structured bindings allow you to unpack the elements of an array, a struct, or a tuple-like object into individual variables. This simplifies accessing the members of these types.
What is the purpose of the std::optional? (C++17)
  • std::optional is a class template that represents an optional value. It can either contain a value of a specific type or be empty (represent no value). It is useful for functions that might or might not return a value, providing a more explicit way to handle the absence of a value than using null pointers or special sentinel values.
What is the purpose of the std::variant? (C++17)
  • std::variant is a type-safe union. It can hold a value of one of a specified set of types. It is useful when a variable can hold one of several different types, providing type safety and avoiding the issues associated with C-style unions.
What is the purpose of the std::any? (C++17)
  • std::any is a type-safe container for a single value of any type. It can hold values of different types at different times. It is useful when you need to store values of arbitrary types, although it involves some overhead compared to std::variant.
What is the purpose of the spaceship operator (<=>)? (C++20)
  • The spaceship operator (three-way comparison operator) simplifies the implementation of comparison operators (<,>, <=, >=, ==, !=). By overloading <=>, the compiler can automatically synthesize the other comparison operators, reducing boilerplate code.
What is a coroutine? (C++20)
  • Coroutines are a language feature that allows functions to be suspended and resumed. They are useful for implementing asynchronous operations, generators, and state machines in a more sequential and readable style compared to traditional callback-based approaches or complex state management.
What is a concept? (C++20)
  • Concepts are a language feature that provides a way to constrain template parameters based on their properties or behavior. They define requirements that a type must satisfy to be used with a template. Concepts improve compile-time error messages and make template code more readable and understandable.
What is the difference between a class template and a concept?
  • A class template is a blueprint for creating a family of classes based on type parameters.
  • A concept defines a set of requirements that a type must satisfy to be used as a template argument. Concepts are used to constrain templates, making them more robust and providing better error messages.
What are modules? (C++20)
  • Modules are a new way to organize and structure C++ code, intended to replace the header file mechanism. Modules provide better encapsulation, faster compilation times, and avoid issues like the order of header includes and macro pollution.
What is the purpose of the [[likely]] and [[unlikely]] attributes? (C++20)
  • These attributes are hints to the compiler about the likelihood of a certain code path being taken. They can help the compiler optimize the code for better performance by arranging instructions more efficiently.
What is the purpose of the std::span? (C++20)
  • std::span is a lightweight view over a contiguous sequence of objects (like an array or a part of a vector). It provides a safe way to pass sequences of data to functions without copying the data or needing explicit size parameters.
What is the purpose of the std::jthread? (C++20)
  • std::jthread is a joinable thread class that automatically joins the thread when it goes out of scope. It simplifies thread management compared to std::thread, which requires explicit joining or detaching.
What is the purpose of the constinit specifier? (C++20)
  • The constinit specifier indicates that a variable must be initialized with a constant expression at compile time. It is stricter than constexpr for initialization and ensures that the variable is initialized before any dynamic initialization takes place.
What is the purpose of the consteval specifier? (C++20)
  • The consteval specifier indicates that a function must be evaluated at compile time. Functions declared with consteval are called immediate functions.
What is the difference between constexpr and consteval?
  • constexpr: A function can be evaluated at compile time if possible, but can also be evaluated at runtime.
  • consteval: A function *must* be evaluated at compile time. It cannot be called in a context that requires runtime evaluation.
What is the purpose of the using enum declaration? (C++20)
  • The using enum declaration brings the enumerators of an enumeration into the current scope without needing to qualify them with the enum name. This improves readability when working with enums.
What is the purpose of the std::format? (C++20)
  • std::format provides a modern and type-safe way to format strings, similar to Python's str.format(). It is generally preferred over C-style printf or iostream manipulators for complex formatting.
What is the purpose of the std::source_location? (C++20)
  • std::source_location provides information about the source code location (file name, line number, column, function name) where it is captured. It is useful for logging, debugging, and creating more informative error messages.
What is the purpose of the std::span? (revisited)
  • std::span provides a non-owning view over a contiguous sequence of elements. It is a safe and efficient way to pass arrays or parts of containers to functions without copying.
What is the purpose of the std::ranges library? (C++20)
  • The std::ranges library provides a new way to work with algorithms and containers. It introduces the concept of ranges (sequences of elements that can be iterated over) and allows for more functional and composable operations on data.
What is the purpose of the std::chrono library?
  • The std::chrono library provides facilities for dealing with time, including durations, time points, and clocks. It is used for measuring time intervals, working with dates and times, and implementing timed operations.
What is the difference between std::vector and std::vector?
  • std::vector is a specialized template that is optimized for space. It stores boolean values as individual bits rather than full bytes. This can save memory but makes element access potentially slower and means its elements are not guaranteed to be contiguous.
  • std::vector stores each character as a full byte, providing efficient access and contiguous storage.
What is the purpose of the std::initializer_list? (revisited)
  • std::initializer_list allows you to initialize containers or call functions with a list of values enclosed in curly braces ({}).
What is the difference between {} initialization and () initialization?
  • {} (Brace initialization or uniform initialization): Can be used for direct and copy initialization. It prevents narrowing conversions (implicit conversions that might lose data). It is generally preferred for its consistency and safety.
  • () (Parentheses initialization): Used for direct initialization. Allows narrowing conversions.
What is the purpose of the std::cout.flush()?
  • std::cout.flush() explicitly flushes the output buffer associated with std::cout. This ensures that any buffered output is immediately written to the destination (usually the console).
What is the difference between a pointer to a member and a pointer to a function?
  • Pointer to a member: A pointer that stores the address of a non-static data member or member function of a class. Its syntax is different from regular pointers.
  • Pointer to a function: A pointer that stores the address of a function (either a non-member function or a static member function).
What is the purpose of the mutable keyword? (revisited)
  • The mutable keyword allows a data member of a class to be modified even if the object is declared as const or accessed through a const member function. It is used for data members that do not affect the logical state of the object.
What is the difference between a shallow copy and a deep copy? (revisited)
  • Shallow Copy: Copies the pointer value, leading to multiple objects sharing the same underlying resource. Dangerous if resources need individual management.
  • Deep Copy: Creates a new copy of the underlying resource, ensuring each object has its own independent resource. Necessary when managing dynamic memory or other resources.
What is the purpose of the const keyword? (revisited)
  • The const keyword is used to indicate that a variable or object cannot be modified after initialization. It helps enforce immutability and allows the compiler to perform optimizations.
What is the difference between a raw pointer and a smart pointer?
  • Raw pointer: A basic pointer that stores a memory address. Manual memory management (new/delete) is required, which can lead to memory leaks or dangling pointers.
  • Smart pointer: An object that wraps a raw pointer and provides automatic memory management using RAII. Helps prevent memory leaks and dangling pointers.
What is the purpose of the std::unique_ptr? (revisited)
  • std::unique_ptr is a smart pointer that provides exclusive ownership of a dynamically allocated object. It ensures that the object is deallocated when the unique_ptr goes out of scope.
What is the purpose of the std::shared_ptr? (revisited)
  • std::shared_ptr is a smart pointer that allows multiple pointers to share ownership of a dynamically allocated object. The object is deallocated when the last shared_ptr pointing to it is destroyed.
What is the purpose of the std::weak_ptr? (revisited)
  • std::weak_ptr is a non-owning smart pointer that provides a non-owning reference to an object managed by a std::shared_ptr. It is used to break circular references and observe an object without extending its lifetime.
What is the purpose of the std::allocator?
  • std::allocator is the default allocator used by STL containers. It is responsible for managing the memory used by the container's elements (allocating and deallocating memory). You can provide custom allocators to control memory management behavior.
What is the difference between a container adaptor and a container?
  • Container: A data structure that stores elements (e.g., vector, list, map).
  • Container Adaptor: Provides a different interface to an existing container, restricting the operations that can be performed (e.g., stack is an adaptor over a deque or list, providing LIFO behavior).
What is the purpose of the std::string class?
  • std::string is a class in the C++ standard library that represents sequences of characters (strings). It provides features like dynamic sizing, various string manipulation operations, and is generally safer and more convenient than C-style character arrays.
What is the difference between char[] and std::string?
  • char[] (C-style string): A null-terminated character array. Fixed size (for static arrays). Requires manual memory management and string manipulation using functions from . Can lead to buffer overflows if not handled carefully.
  • std::string: A class that represents a dynamic string. Automatically manages memory. Provides member functions for various string operations. Generally safer and more convenient.
What is the purpose of the std::stringstream?
  • std::stringstream allows you to treat a string as an input or output stream. It is useful for parsing strings or building strings programmatically using stream insertion and extraction operators.
What is the purpose of the std::unique algorithm?
  • The std::unique algorithm removes consecutive duplicate elements from a range. It does not actually remove elements from the container; it rearranges them so that unique elements appear at the beginning and returns an iterator to the end of the unique range. You typically need to use the container's erase method with the returned iterator to truly remove the duplicate elements.
What is the purpose of the std::sort algorithm?
  • The std::sort algorithm sorts the elements in a range in ascending order by default. It uses a fast sorting algorithm (typically IntroSort).
What is the purpose of the std::find algorithm?
  • The std::find algorithm searches for the first occurrence of a specific value within a range and returns an iterator to that element. If the value is not found, it returns an iterator to the end of the range.
What is the purpose of the std::copy algorithm?
  • The std::copy algorithm copies elements from one range to another range. It takes input iterators for the source range and an output iterator for the destination range.
What is the purpose of the std::transform algorithm?
  • The std::transform algorithm applies a function or functor to each element in an input range and stores the result in an output range.
What is the difference between passing by value, by reference, and by pointer? (revisited with C++)
  • Pass by Value: A copy of the argument is passed. Changes inside the function do not affect the original.
  • Pass by Reference: An alias to the original argument is passed. Changes inside the function affect the original. Efficient for large objects as it avoids copying.
  • Pass by Pointer: The memory address of the argument is passed. Allows the function to modify the original value by dereferencing the pointer. Can be nullptr.
What is the purpose of the const keyword in function parameters? (revisited)
  • Using const with function parameters (e.g., void myFunction(const MyClass& obj)) indicates that the function will not modify the value of the parameter. This allows the compiler to enforce immutability and helps users understand the function's behavior. For objects, passing by const reference is often preferred over passing by value to avoid unnecessary copying.
What is the purpose of the std::atomic library? (C++11)
  • The std::atomic library provides atomic types and operations. Atomic operations are guaranteed to complete without interruption from other threads, making them useful for low-level synchronization and avoiding race conditions on simple data types without using mutexes.
What is the purpose of the std::packaged_task? (C++11)
  • std::packaged_task is a class template that wraps a callable entity (function, lambda, function object) and allows its result to be retrieved asynchronously via a std::future. It is often used to launch tasks in separate threads.
What is the purpose of the std::async? (C++11)
  • std::async is a function template that launches a task asynchronously (potentially in a new thread) and returns a std::future to access the result. It simplifies the process of running tasks in separate threads compared to manually managing std::thread and std::promise.
What is the difference between std::thread and std::async?
  • std::thread: Creates and manages a thread explicitly. You are responsible for joining or detaching the thread.
  • std::async: Launches a task asynchronously, and the execution might happen in a new thread or be deferred. The result is accessed via a std::future, and the underlying thread (if any) is automatically managed when the future is destroyed or waited upon.
What is the purpose of the std::exception class?
  • std::exception is the base class for all standard C++ exceptions. It provides a common interface for exception handling, allowing you to catch generic exceptions and access information about the error (e.g., using the what() method).
What is the difference between catching by value, by reference, and by pointer?
  • Catch by Value: Catches a copy of the exception object. Can lead to object slicing if the exception object is a derived class.
  • Catch by Reference: Catches a reference to the exception object. Preferred as it avoids slicing and unnecessary copying. Catching by const reference (e.g., catch (const std::exception& e)) is common and recommended.
  • Catch by Pointer: Catches a pointer to the exception object. Less common and generally not recommended unless you have specific reasons to use pointers.
What is the purpose of the throw; statement?
  • A bare throw; statement within a catch block rethrows the currently caught exception. This is useful for propagating the exception up the call stack after performing some handling or logging.
What is the purpose of the std::terminate() function?
  • The std::terminate() function is called when the program needs to terminate due to an unhandled exception or certain other error conditions. By default, it calls abort().
What is the purpose of the std::uncaught_exceptions() function? (C++11)
  • std::uncaught_exceptions() returns the number of uncaught exceptions currently being handled. It can be useful in destructors or exception handlers to determine if an exception is in flight and adjust resource management accordingly.
What is the purpose of the std::nested_exception? (C++11)
  • std::nested_exception is a class that can be used to chain exceptions. When an exception is caught and another exception is thrown from within the handler, you can use std::nested_exception to preserve information about the original exception.
What is the purpose of the std::exception_ptr? (C++11)
  • std::exception_ptr is a smart pointer-like object that can hold a pointer to an exception object. It allows you to capture an exception in one context (e.g., a thread) and rethrow it in another context.
What is the purpose of the std::future? (revisited)
  • std::future represents the result of an asynchronous operation. It allows you to wait for the result to become available and retrieve it.
What is the purpose of the std::promise? (revisited)
  • std::promise is used to set a value or an exception that will be retrieved by a corresponding std::future. It provides a way for one part of a program to communicate a result to another part, often across thread boundaries.
What is the purpose of the std::packaged_task? (revisited)
  • std::packaged_task wraps a callable entity and associates it with a std::future. When the task is executed, its result or exception is stored in the shared state, which can be accessed via the associated future.
What is the purpose of the std::async? (revisited)
  • std::async is a utility function that simplifies launching a task asynchronously and obtaining a std::future to its result. It can choose to run the task in a new thread or defer its execution.
What is the purpose of the std::thread? (revisited)
  • std::thread is the basic class for creating and managing threads in C++. You explicitly create a thread and are responsible for joining or detaching it to avoid program termination issues.
What is the difference between joining and detaching a thread?
  • Joining: The calling thread waits for the target thread to finish execution. This is necessary to ensure that the resources used by the thread are properly cleaned up.
  • Detaching: The target thread becomes independent of the calling thread. When the detached thread finishes, its resources are automatically reclaimed by the operating system. Detached threads cannot be joined later.
What is a race condition?
  • A race condition occurs when the behavior of a program depends on the unpredictable timing of multiple threads or processes accessing shared resources. This can lead to incorrect results or program crashes. Synchronization mechanisms (like mutexes, atomic operations) are used to prevent race conditions.
What is a deadlock?
  • A deadlock is a situation in which two or more threads or processes are blocked indefinitely, waiting for each other to release resources that they need. This typically happens when threads acquire multiple locks in different orders.
What is the purpose of the std::lock_guard? (revisited)
  • std::lock_guard is a simple RAII wrapper around a mutex that provides automatic locking and unlocking. It is used to ensure that a mutex is acquired when the lock_guard is created and released when it goes out of scope, even in the presence of exceptions.
What is the purpose of the std::unique_lock? (revisited)
  • std::unique_lock is a more flexible RAII wrapper around a mutex. It allows for deferred locking, timed locking, and transferring ownership of the lock. It is often used with condition variables.
What is the purpose of the std::condition_variable? (revisited)
  • std::condition_variable is a synchronization primitive used to block one or more threads until another thread notifies them. It is typically used in conjunction with a mutex to wait for a specific condition to become true.
What is the purpose of the std::atomic library? (revisited)
  • The std::atomic library provides types and operations that are guaranteed to be atomic (indivisible). This is crucial for low-level synchronization without explicit locks, especially for simple data types accessed by multiple threads.
What is the purpose of the std::this_thread namespace? (C++11)
  • The std::this_thread namespace provides functions for accessing and manipulating the current thread, such as getting its ID (get_id()) or putting it to sleep (sleep_for(), yield()).
What is the difference between std::decay and std::remove_reference and std::remove_cv?
  • std::remove_reference::type: Removes reference from type T (e.g., int& becomes int).
  • std::remove_cv::type: Removes top-level const and volatile qualifiers from type T (e.g., const int becomes int).
  • std::decay::type: Applies a series of transformations to type T to make it suitable for passing by value. It removes references, removes top-level const/volatile, and converts arrays and functions to pointers.
What is the purpose of the std::tuple? (C++11)
  • std::tuple is a fixed-size collection of elements of potentially different types. It is a generalization of std::pair and is useful for returning multiple values from a function or grouping related data.
What is the purpose of the std::get function with tuples?
  • The std::get function is used to access elements of a std::tuple by index (at compile time) or by type (if the type is unique in the tuple).
What is the purpose of the std::tie function? (C++11)
  • std::tie creates a tuple of references. It is often used to unpack the elements of a tuple or pair into existing variables.
What is the purpose of the std::move? (final revisit)
  • std::move is a utility function that casts its argument to an rvalue reference. It is used to indicate that an object's resources can be moved from, enabling the compiler to select the move constructor or move assignment operator for efficiency.