C++ Interview Questions and Answers

100 C++ Interview Questions and Answers
  1. What is C++?

    • Answer: C++ is a general-purpose, object-oriented programming (OOP) language that is an extension of the C programming language. It supports various programming paradigms, including procedural, object-oriented, and generic programming.
  2. What are the basic building blocks of C++?

    • Answer: Variables, data types, operators, control structures (if-else, loops), functions, classes, and objects.
  3. Explain the difference between `int`, `float`, and `double` data types.

    • Answer: `int` stores integers (whole numbers), `float` stores single-precision floating-point numbers (numbers with decimal points), and `double` stores double-precision floating-point numbers (more precise than `float`).
  4. What is a pointer in C++?

    • Answer: A pointer is a variable that holds the memory address of another variable. It's declared using the `*` symbol.
  5. What is the purpose of the `new` and `delete` operators?

    • Answer: `new` allocates memory dynamically at runtime, while `delete` deallocates dynamically allocated memory to prevent memory leaks.
  6. Explain the concept of references in C++.

    • Answer: A reference is an alias for an existing variable. It's declared using the `&` symbol. Once initialized, a reference cannot be changed to refer to a different variable.
  7. What is a function in C++?

    • Answer: A function is a block of code that performs a specific task. It can take arguments (input) and return a value (output).
  8. What is function overloading?

    • Answer: Function overloading allows multiple functions with the same name but different parameters (number, type, or order). The compiler determines which function to call based on the arguments provided.
  9. What is operator overloading?

    • Answer: Operator overloading allows defining the behavior of operators (e.g., +, -, *, /) for user-defined types (classes).
  10. Explain the difference between `const` and `static` keywords.

    • Answer: `const` indicates that a variable's value cannot be changed after initialization. `static` for a local variable means it retains its value between function calls; for a class member, it means there's only one copy shared among all objects of that class.
  11. What are access specifiers in C++?

    • Answer: Access specifiers (`public`, `private`, `protected`) control the accessibility of class members (data and functions) from outside the class.
  12. What is inheritance in C++?

    • Answer: Inheritance is a mechanism where a class (derived class) inherits properties and methods from another class (base class). It promotes code reusability and establishes an "is-a" relationship.
  13. Explain different types of inheritance.

    • Answer: Single inheritance (one base class), multiple inheritance (multiple base classes), multilevel inheritance (a derived class inherits from another derived class), hierarchical inheritance (multiple derived classes from one base class), hybrid inheritance (combination of multiple inheritance types).
  14. What is polymorphism?

    • Answer: Polymorphism allows objects of different classes to be treated as objects of a common type. It's often implemented using virtual functions and inheritance.
  15. What is a virtual function?

    • Answer: A virtual function is a member function declared using the `virtual` keyword. It allows dynamic dispatch, meaning the correct function to call is determined at runtime based on the object's type.
  16. What is an abstract class?

    • Answer: An abstract class is a class that cannot be instantiated. It serves as a base class for other classes and often contains pure virtual functions (functions declared with `= 0`).
  17. What is a pure virtual function?

    • Answer: A pure virtual function is a virtual function declared with `= 0`. It must be implemented in derived classes; otherwise, the derived class also becomes abstract.
  18. What is an exception?

    • Answer: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. C++ uses `try`, `catch`, and `throw` for exception handling.
  19. Explain `try`, `catch`, and `throw` keywords.

    • Answer: `try` encloses code that might throw an exception. `catch` handles exceptions of specific types. `throw` throws an exception object.
  20. What is a template in C++?

    • Answer: Templates allow writing generic code that can work with different data types without being rewritten for each type. They are used for functions and classes.
  21. What is the Standard Template Library (STL)?

    • Answer: The STL is a library of container classes (e.g., `vector`, `list`, `map`), algorithms, and iterators that provides reusable data structures and algorithms.
  22. Explain the difference between `vector` and `array` in STL.

    • Answer: `vector` is a dynamic array that can resize automatically, while `array` is a fixed-size array with a size known at compile time.
  23. What is a smart pointer?

    • Answer: A smart pointer is a class that acts like a pointer but automatically manages memory, preventing memory leaks. Examples include `unique_ptr`, `shared_ptr`, and `weak_ptr`.
  24. Explain the difference between `unique_ptr`, `shared_ptr`, and `weak_ptr`.

    • Answer: `unique_ptr` provides exclusive ownership of a dynamically allocated object. `shared_ptr` allows shared ownership among multiple pointers. `weak_ptr` is a non-owning pointer that can detect if the object it points to has been deleted.
  25. What is RAII (Resource Acquisition Is Initialization)?

    • Answer: RAII is a C++ programming idiom where resource management (like memory allocation) is tied to the object's lifetime. Resources are acquired when an object is created and released when it's destroyed.
  26. What is the difference between a class and a struct in C++?

    • Answer: The main difference is the default access specifier: `class` defaults to `private`, while `struct` defaults to `public`.
  27. What is name mangling?

    • Answer: Name mangling is the process by which the compiler transforms function and variable names into unique internal names to handle function overloading and linking.
  28. What is a namespace?

    • Answer: A namespace is a declarative region that provides a scope to prevent naming conflicts between identifiers.
  29. What is the `this` pointer?

    • Answer: The `this` pointer is a hidden pointer within a class's member functions that points to the current object instance.
  30. What is the difference between `malloc()` and `new`?

    • Answer: `malloc()` allocates raw memory without constructor calls, while `new` allocates memory and calls the constructor of the object being created.
  31. What is the difference between `free()` and `delete`?

    • Answer: `free()` deallocates memory allocated by `malloc()`, while `delete` deallocates memory allocated by `new` and calls the destructor of the object.
  32. What are iterators in C++?

    • Answer: Iterators are objects that act like pointers, allowing traversal of elements in containers (like vectors and lists) in a generic way.
  33. Explain different types of iterators.

    • Answer: Input iterators, output iterators, forward iterators, bidirectional iterators, random access iterators.
  34. What is a lambda expression?

    • Answer: A lambda expression is an anonymous function (a function without a name) that can be defined inline.
  35. What is move semantics?

    • Answer: Move semantics allows efficient transfer of resources (like dynamically allocated memory) from one object to another without copying. It uses rvalue references and move constructors/assignment operators.
  36. What is RVO (Return Value Optimization)?

    • Answer: RVO is a compiler optimization that avoids unnecessary copying of objects when they are returned from functions.
  37. What is NRVO (Named Return Value Optimization)?

    • Answer: NRVO is a compiler optimization similar to RVO, but it applies specifically when the returned object has a name (e.g., a local variable).
  38. Explain the concept of perfect forwarding.

    • Answer: Perfect forwarding is a technique used in templates to forward function arguments without making unnecessary copies or moves. It uses universal references.
  39. What are variadic templates?

    • Answer: Variadic templates allow functions and classes to accept a variable number of arguments of different types.
  40. What is the difference between `std::copy` and `std::memcpy`?

    • Answer: `std::copy` works with any type and uses iterators, while `std::memcpy` works only with raw bytes and uses pointers; `std::copy` is safer and more type-safe.
  41. What is the difference between a left-value and a right-value?

    • Answer: A left-value is an expression that can appear on the left side of an assignment operator (has a persistent location in memory). A right-value is an expression that cannot appear on the left side (e.g., a temporary object).
  42. What is the role of the preprocessor in C++?

    • Answer: The preprocessor processes the source code before compilation, handling directives like `#include`, `#define`, `#ifdef`, etc.
  43. What are header files and why are they used?

    • Answer: Header files contain declarations of functions, classes, and variables. They are included in source files using `#include` to make those declarations available.
  44. What is the purpose of the `using namespace` directive?

    • Answer: The `using namespace` directive makes identifiers from a specific namespace directly accessible without the namespace prefix.
  45. What is a friend function?

    • Answer: A friend function is a function declared as a friend of a class. It has access to the class's private and protected members.
  46. What is a friend class?

    • Answer: A friend class is a class declared as a friend of another class. All its member functions have access to the private and protected members of the befriended class.
  47. Explain the difference between early and late binding.

    • Answer: Early binding (static binding) resolves function calls at compile time. Late binding (dynamic binding) resolves function calls at runtime, using virtual functions.
  48. What is the Standard Template Library (STL) algorithm `std::sort`?

    • Answer: `std::sort` is a powerful algorithm that sorts a range of elements in ascending order using an efficient sorting algorithm (usually IntroSort).
  49. What is the difference between `auto` and `decltype`?

    • Answer: `auto` lets the compiler deduce the type of a variable from its initializer. `decltype` extracts the type of an expression without evaluating it.
  50. What are smart pointers and why are they useful?

    • Answer: Smart pointers automatically manage the lifetime of dynamically allocated objects, preventing memory leaks and dangling pointers.
  51. How do you handle exceptions in C++?

    • Answer: Exceptions are handled using `try`, `catch`, and `throw` blocks. The `try` block contains code that might throw an exception; `catch` blocks handle different exception types; `throw` throws an exception object.
  52. What is the role of a destructor?

    • Answer: A destructor is a special member function of a class that is called automatically when an object goes out of scope or is explicitly deleted using `delete`. It's used to release resources held by the object.
  53. Explain the concept of copy constructors.

    • Answer: A copy constructor is a special member function that creates a copy of an existing object. It's automatically called when an object is initialized from another object of the same type.
  54. Explain the concept of assignment operators.

    • Answer: An assignment operator (usually `=`) is a special member function that assigns the values of one object to another object of the same type. It's called when using the assignment operator between two objects.
  55. What is the rule of five/zero?

    • Answer: The rule of five (or zero) describes when you need to define the destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator. If you define one, you often need the others to ensure proper resource management. The rule of zero advocates for avoiding these explicit definitions where possible by using smart pointers and value semantics.
  56. What is a container in C++?

    • Answer: A container is a data structure that stores a collection of objects. The STL provides many standard containers, such as `vector`, `list`, `map`, `set`, etc.
  57. What is an iterator in C++?

    • Answer: An iterator is an object that acts like a pointer, allowing you to traverse the elements of a container in a generic way.
  58. What is the difference between `std::vector` and `std::list`?

    • Answer: `std::vector` provides random access to elements with contiguous storage, while `std::list` provides only sequential access with non-contiguous storage. `vector` is generally faster for element access, while `list` is faster for insertions and deletions in the middle.
  59. What is the difference between `std::map` and `std::unordered_map`?

    • Answer: `std::map` stores elements in a sorted order based on the key, providing logarithmic time complexity for search, insertion, and deletion. `std::unordered_map` uses a hash table, providing average constant time complexity for these operations but no guaranteed order.
  60. What is a function object (functor)?

    • Answer: A function object is a class that overloads the `operator()` allowing it to be called like a function.
  61. What is the difference between pass by value, pass by reference, and pass by pointer?

    • Answer: Pass by value creates a copy of the argument. Pass by reference passes a reference to the argument, avoiding copying. Pass by pointer passes a pointer to the argument's memory location.
  62. What is a memory leak?

    • Answer: A memory leak occurs when dynamically allocated memory is not freed, leading to gradual exhaustion of available memory.
  63. What is a dangling pointer?

    • Answer: A dangling pointer points to memory that has been deallocated or freed.
  64. What is the difference between const correctness and immutability?

    • Answer: Const correctness is about preventing accidental modification of data through the use of the `const` keyword. Immutability means that an object cannot be changed after it's created.
  65. Explain the concept of compile-time polymorphism.

    • Answer: Compile-time polymorphism (static polymorphism) is achieved through function overloading and operator overloading. The compiler determines which function to call at compile time.
  66. Explain the concept of runtime polymorphism.

    • Answer: Runtime polymorphism (dynamic polymorphism) is achieved through virtual functions and inheritance. The correct function to call is determined at runtime based on the object's type.
  67. What is the difference between a class and an object?

    • Answer: A class is a blueprint for creating objects. An object is an instance of a class.
  68. What is the difference between static and dynamic linking?

    • Answer: Static linking incorporates library code directly into the executable at compile time. Dynamic linking links the library at runtime.
  69. What is the difference between a declaration and a definition?

    • Answer: A declaration introduces a name and its type to the compiler without allocating memory. A definition allocates memory and provides the implementation.
  70. What is the role of the linker?

    • Answer: The linker combines object files and libraries to create an executable file.
  71. What are the different storage classes in C++?

    • Answer: `auto`, `register`, `static`, `extern`, `mutable`.
  72. What is a volatile keyword?

    • Answer: The `volatile` keyword tells the compiler that a variable's value might be changed unexpectedly (e.g., by hardware or another thread), preventing optimizations that might assume the variable's value remains constant.
  73. What is the Standard Template Library (STL) algorithm `std::find`?

    • Answer: `std::find` searches for a specific value within a range of elements and returns an iterator to the first occurrence if found, otherwise returns an iterator to the end of the range.
  74. What is the Standard Template Library (STL) algorithm `std::transform`?

    • Answer: `std::transform` applies a given function to each element of a range and stores the results in another range.
  75. What is the difference between `sizeof` and `strlen`?

    • Answer: `sizeof` is a compile-time operator that gives the size of a data type or variable in bytes. `strlen` is a runtime function that gives the length of a null-terminated C-style string.
  76. What are the different ways to initialize a `std::vector`?

    • Answer: Several ways exist, including default construction, specifying size, specifying size and value, and using an initializer list.
  77. How do you implement a singly linked list in C++?

    • Answer: A singly linked list consists of nodes, where each node points to the next node in the sequence. You'd need a Node class with data and a pointer to the next node, and a LinkedList class to manage the list.
  78. How do you implement a doubly linked list in C++?

    • Answer: Similar to a singly linked list but each node has pointers to both the next and previous nodes.
  79. How do you implement a binary search tree in C++?

    • Answer: A binary search tree (BST) is a tree data structure where the left subtree contains nodes with keys less than the root node's key, and the right subtree contains nodes with keys greater than the root node's key. Recursive insertion and searching are common implementations.
  80. What is a stack in C++?

    • Answer: A stack is a LIFO (Last-In, First-Out) data structure. Elements are added (pushed) and removed (popped) from the top.
  81. What is a queue in C++?

    • Answer: A queue is a FIFO (First-In, First-Out) data structure. Elements are added (enqueued) at the rear and removed (dequeued) from the front.

Thank you for reading our blog post on 'C++ Interview Questions and Answers'.We hope you found it informative and useful.Stay tuned for more insightful content!