Top Interview Questions and Answers on C++ ( 2025 )
Here are some common C++ interview questions along with their answers:
1. What is C++?
Answer: C++ is a general-purpose programming language created by Bjarne Stroustrup at Bell Labs in the late 1970s. It is an extension of the C programming language and includes object-oriented features, such as classes and inheritance, along with low-level memory manipulation capabilities.
2. What are the main features of C++?
Answer:
- Object-Oriented: Supports classes, objects, inheritance, polymorphism, and encapsulation.
- Standard Template Library (STL): Provides powerful template classes for data structures and algorithms.
- Memory Management: Includes features like pointers and dynamic memory allocation.
- Rich Functionality: Supports function overloading, operator overloading, and templates.
- Low-Level Manipulation: Allows direct manipulation of hardware and memory.
3. What is the difference between `struct` and `class` in C++?
Answer: In C++, `struct` and `class` are fundamentally similar in that they can both contain data and functions. The primary difference is:
- Members of a `struct` are public by default.
- Members of a `class` are private by default.
4. What is a constructor and a destructor?
Answer:
- Constructor: A special member function that initializes objects. It has the same name as the class and no return type. It is called automatically when an object is created.
- Destructor: Also a special member function that is invoked when an object goes out of scope or is explicitly deleted. It has the same name as the class, but is preceded by a tilde (~) and does not have any return type or parameters.
5. What is the difference between a pointer and a reference in C++?
Answer:
- A pointer can be reassigned to point to different objects and can be null. It is declared using an asterisk (`*`) and can be manipulated using arithmetic.
- A reference, on the other hand, is an alias for an existing variable and cannot be null. It must be initialized when declared and cannot be made to refer to another variable once set.
6. What is polymorphism in C++ and how is it implemented?
Answer: Polymorphism is the ability to present the same interface for different underlying data types. In C++, polymorphism can be achieved through:
- Compile-time polymorphism: Function overloading and operator overloading.
- Runtime polymorphism: Achieved through inheritance and virtual functions. When a base class reference is used to refer to a derived class object, the correct overridden method is called based on the actual object type at runtime.
7. What are virtual functions in C++?
Answer: A virtual function is a member function in a base class that can be overridden in a derived class. It is declared by placing the keyword `virtual` before the function signature in the base class. Virtual functions enable runtime polymorphism, allowing the program to decide which function to invoke based on the object type.
8. Can you explain RAII in C++?
Answer: RAII stands for Resource Acquisition Is Initialization. It is a programming idiom that ties resource management (like dynamic memory, file handles, etc.) to the lifetime of objects. Resources are acquired during object creation and released during destruction. This helps ensure that resources are properly cleaned up, preventing leaks and ensuring exception safety.
9. What is memory leak, and how can you prevent it?
Answer: A memory leak occurs when a program allocates memory on the heap but does not release it after use, leading to a gradual increase in memory consumption. To prevent memory leaks:
- Use smart pointers (`std::unique_ptr`, `std::shared_ptr`) which automatically manage memory.
- Ensure manual `delete` calls correspond to every `new`.
- Utilize tools like Valgrind to detect memory leaks in applications.
10. What is the difference between deep copy and shallow copy?
Answer:
- Shallow Copy: It creates a new object but copies the values of the fields from the original object. If fields are pointers, both the original and the copied object point to the same memory location.
- Deep Copy: It creates a new object and also creates copies of dynamically allocated memory pointed to by the original object's fields. The copied object gets its copy of the data, preventing unintended side effects.
These questions cover foundational concepts and are often encountered in C++ interviews. It's a good idea to delve deeper into each topic by practicing with coding examples and problems related to them.
Here are some advanced C++ interview questions along with their answers:
1. What are the main differences between `std::vector`, `std::list`, and `std::deque`?
Answer:
- std::vector:
- Dynamic array that provides fast random access.
- Data is stored contiguously in memory, leading to cache-friendly access patterns.
- Insertion and deletion of elements at the end is fast (amortized O(1)), but slow (O(n)) for those in the middle due to shifting elements.
- std::list:
- Doubly linked list, allowing fast insertion and deletion anywhere in the list (O(1) for known positions).
- No random access (O(n) for access by index).
- More memory overhead due to storing pointers for each element.
- std::deque:
- Double-ended queue that allows fast insertion and deletion at both ends.
- Provides random access like `std::vector` but can be less cache-friendly because elements are not guaranteed to be contiguous.
- Offers better performance in scenarios requiring frequent insertions/deletions at both ends.
2. Explain the concept of templates in C++.
Answer: Templates in C++ allow for generic programming, enabling the creation of functions and classes that can operate with any data type. There are two main types:
- Function Templates: Allow you to write a function that works with any data type.
```cpp
template <typename T>
T add(T a, T b) {
return a + b;
}
```
- Class Templates: Enable creating a class that can handle any data type.
```cpp
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T getValue() { return value; }
};
```
3. What is the purpose of the `constexpr` keyword?
Answer: The `constexpr` keyword is used to declare that it is possible for the value of a variable or function to be computed at compile time. This enables more optimizations and allows the use of certain variables in contexts where compile-time constant expressions are required (like array sizes, template parameters, etc.). Example:
```cpp
constexpr int square(int x) {
return x * x;
}
```
4. What are smart pointers, and what are the differences between `std::unique_ptr`, `std::shared_ptr`, and `std::weak_ptr`?
Answer:
- std::unique_ptr:
- Represents exclusive ownership of an object. Only one `unique_ptr` can own the object at a time. When the `unique_ptr` goes out of scope, the object is automatically deleted.
- Cannot be copied, only moved.
- std::shared_ptr:
- Represents shared ownership. Multiple `shared_ptr` instances can own the same object. The object is deleted when the last `shared_ptr` owning it is destroyed or reset.
- Uses reference counting to track the number of `shared_ptr`s pointing to an object.
- std::weak_ptr:
- Works with `shared_ptr` to prevent circular references. It does not contribute to the reference count. `weak_ptr` is used to observe an object managed by `shared_ptr` without affecting its lifetime.
5. Explain the Rule of Five in C++.
Answer: The Rule of Five states that if a class defines one or more of the following special member functions, it should probably explicitly define all five:
1. Destructor
2. Copy Constructor
3. Copy Assignment Operator
4. Move Constructor
5. Move Assignment Operator
This is important for proper resource management, especially when dealing with dynamic memory or other resources. Failing to correctly handle these can lead to memory leaks, double deletions, or resource misuse.
6. What are lambda expressions, and how are they used in C++?
Answer: Lambda expressions are a feature introduced in C++11 that allow you to define anonymous functions directly in the code. They are particularly useful for short, throwaway functions, like when used as arguments to algorithms. The basic syntax is:
```cpp
[capture](parameters) -> return_type {
// function body
}
```
Example:
```cpp
auto add = [](int a, int b) { return a + b; };
int sum = add(2, 3); // sum = 5
```
7. What is the difference between static and dynamic polymorphism?
Answer:
- Static Polymorphism: Resolved at compile time. Achieved through templates and function overloading. The method to call is determined based on the parameter types at compile time.
- Dynamic Polymorphism: Resolved at runtime. Achieved through inheritance and virtual functions. The method to call is determined based on the object's actual type at runtime, allowing for behavior that can be changed at runtime.
8. Can you explain the use of `std::move` and `std::forward`?
Answer:
- std::move: A utility function that converts its argument into an rvalue reference. It is used to enable move semantics, allowing resources to be transferred instead of copied:
```cpp
std::string str = "Hello";
std::string str2 = std::move(str); // 'str' is now in a valid but unspecified state
```
- std::forward: A utility function used in template programming to cast an argument to an rvalue or lvalue reference, allowing perfect forwarding:
```cpp
template <typename T>
void wrapper(T&& arg) {
func(std::forward<T>(arg)); // Preserves the value category of 'arg'
}
```
9. What are variadic templates in C++?
Answer: Variadic templates allow functions and classes to accept an arbitrary number of template arguments. This feature, introduced in C++11, enables writing more generic code.
Example:
```cpp
template<typename... Args>
void print(Args... args) {
(std::cout << ... << args) << '\n'; // Fold expression, C++17
}
```
10. What is SFINAE (Substitution Failure Is Not An Error)?
Answer: SFINAE is a principle in C++ template programming that states that if substitution of template arguments fails, it is not a compilation error but rather results in the template being ignored. This allows for techniques such as function template overloading based on whether certain types exhibit specific properties.
Example:
```cpp
template<typename T>
auto f(T t) -> decltype(t.someMethod(), void()) {
return t.someMethod();
}
template<typename T>
void f(T t) {
// alternative implementation
}
```
These questions delve into more complex C++ mechanisms and are often encountered in interviews for senior positions or roles requiring advanced C++ knowledge. Familiarity with these concepts can significantly enhance your understanding of the language and its capabilities.