ParthaKuchana.com   Stocks & Technology
Top 25 Advanced C++ Interview Questions and Answers for IT Professionals (2024) Part 2
Top 25 Advanced C++ Interview Questions and Answers for IT Professionals (2024) Part 2


here are another 25 advanced-level C++ interview questions with corresponding answers:

1. What are move constructors and move assignment operators in C++11, and why are they important?

Answer: Move constructors and move assignment operators enable the transfer of resources from one object to another without copying, which is especially useful for managing dynamic memory and resources efficiently. They are indicated by `&&` and allow for the optimization of resource management in cases where temporary objects are used.

2. Explain the concept of perfect forwarding in C++11.

Answer: Perfect forwarding is a technique that preserves the value category (lvalue or rvalue) of function arguments when they are passed to another function. It is typically achieved using `std::forward` in combination with universal references (`T&&`). Example:
```cpp
template
void wrapper(T&& arg) {
func(std::forward(arg));
}
```

3. How do you implement the observer pattern in C++?

Answer: The observer pattern can be implemented using a combination of interfaces, function pointers, or the `std::function` and `std::vector` containers to manage and notify observers. Example:
```cpp
class Observer {
public:
virtual void update() = 0;
};

class Subject {
std::vector observers;
public:
void addObserver(Observer* obs) {
observers.push_back(obs);
}
void notifyObservers() {
for (Observer* obs : observers) {
obs->update();
}
}
};
```

4. What is type erasure in C++?

Answer: Type erasure is a technique that allows code to work with different types in a uniform way, hiding the specific type of an object. This can be achieved using templates and inheritance. `std::function` and `std::any` are examples of type erasure in the C++ standard library.

5. Explain the CRTP (Curiously Recurring Template Pattern) and its uses.

Answer: CRTP is a technique in which a class template is used as a base class and its derived class is passed as the template parameter. This allows for static polymorphism and code reuse. Example:
```cpp
template
class Base {
public:
void interface() {
static_cast(this)->implementation();
}
};

class Derived : public Base {
public:
void implementation() {
// Specific implementation
}
};
```

6. What are variadic templates in C++11 and how are they used?

Answer: Variadic templates allow functions and classes to accept a variable number of arguments. They are defined using `...` in the template parameter list. Example:
```cpp
template
void print(Args... args) {
(std::cout << ... << args) << std::endl;
}

print(1, 2, 3, "hello"); // Output: 123hello
```

7. How do you implement a binary search tree in C++?

Answer: A binary search tree (BST) can be implemented using a class with nodes containing left and right child pointers, and recursive functions for insertion, deletion, and searching. Example:
```cpp
struct Node {
int data;
Node* left;
Node* right;
Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

class BST {
Node* root;
void insert(Node*& node, int value);
bool search(Node* node, int value);
// Additional functions for deletion, traversal, etc.
public:
BST() : root(nullptr) {}
void insert(int value) { insert(root, value); }
bool search(int value) { return search(root, value); }
};

void BST::insert(Node*& node, int value) {
if (!node) node = new Node(value);
else if (value < node->data) insert(node->left, value);
else insert(node->right, value);
}

bool BST::search(Node* node, int value) {
if (!node) return false;
if (value == node->data) return true;
if (value < node->data) return search(node->left, value);
return search(node->right, value);
}
```

8. What is the difference between deep copy and shallow copy in C++?

Answer: A deep copy duplicates all the objects it references, creating independent copies, whereas a shallow copy only copies the top-level objects and references the same memory locations for nested objects. This difference affects how changes to the original objects are reflected in the copies.

9. Explain the use of `std::optional` in C++17.

Answer: `std::optional` is a container that holds a value or indicates the absence of a value. It is used to represent optional or nullable values without using pointers. Example:
```cpp
std::optional opt;
if (opt) {
std::cout << "Value: " << *opt << std::endl;
} else {
std::cout << "No value" << std::endl;
}
```

10. How do you implement exception-safe code in C++?

Answer: Exception-safe code ensures that resources are properly released and program invariants are maintained even when exceptions occur. This can be achieved using RAII, smart pointers, and careful management of resource ownership and exception propagation.

11. What is a virtual destructor and why is it important?

Answer: A virtual destructor ensures that the destructors of derived classes are called when an object is deleted through a base class pointer. This is important for proper resource cleanup in polymorphic classes. Example:
```cpp
class Base {
public:
virtual ~Base() {
// Cleanup code
}
};

class Derived : public Base {
public:
~Derived() override {
// Derived-specific cleanup code
}
};
```

12. Explain the purpose of the `mutable` keyword in C++.

Answer: The `mutable` keyword allows a member of an object to be modified even if the object is declared as `const`. This is useful for data members that are logically mutable, such as caching or lazily initialized values. Example:
```cpp
class Example {
mutable int cache;
public:
int getValue() const {
if (cache == -1) {
cache = computeValue();
}
return cache;
}
};
```

13. How do you implement a state machine in C++?

Answer: A state machine can be implemented using classes or enums to represent states and a function to handle state transitions. Example:
```cpp
enum class State { Idle, Processing, Finished };

class StateMachine {
State currentState;
public:
StateMachine() : currentState(State::Idle) {}
void process() {
switch (currentState) {
case State::Idle:
// Transition logic
currentState = State::Processing;
break;
case State::Processing:
// Transition logic
currentState = State::Finished;
break;
case State::Finished:
// Transition logic
currentState = State::Idle;
break;
}
}
};
```

14. What is the difference between `std::function` and function pointers in C++?

Answer: `std::function` is a polymorphic function wrapper that can store, copy, and invoke any callable target (function, lambda, functor, etc.), while function pointers can only point to functions with a specific signature. `std::function` provides more flexibility and ease of use in modern C++.

15. How do you use `std::tie` for tuple unpacking in C++?

Answer: `std::tie` is used to create a tuple of lvalue references to unpack values from another tuple or pair. Example:
```cpp
std::tuple t = std::make_tuple(1, 2.3, "hello");
int a;
double b;
std::string c;
std::tie(a, b, c) = t; // a = 1, b = 2.3, c = "hello"
```

16. What are expression templates and how do they improve performance in C++?

Answer: Expression templates are a metaprogramming technique used to optimize the evaluation of complex expressions at compile time, avoiding temporary objects and enabling more efficient code. They are often used in numerical libraries. Example:
```cpp
template
struct Vector {
std::vector data;
// Overloaded operators for expression templates
};
```

17. How do you implement a priority queue in C++?

Answer: A priority queue can be implemented using the `std::priority_queue` container adaptor, which provides a max-heap by default. Example:
```cpp
std::priority_queue pq;
pq.push(5);
pq.push(3);
pq.push(8);
std::cout << pq.top() << std::endl; // Output: 8
pq.pop();
```

18. Explain the use of `std::any` in C++17.

Answer: `std::any` is a type-safe container for single values of any type, providing a way to store and retrieve values without knowing their type at compile time. Example:
```cpp
std::any a = 10;
a = std::string("hello");
try {
std::cout << std::any_cast(a) << std::endl;
} catch (const std::bad_any_cast& e) {
std::cout << "Bad cast: " << e.what() << std::endl;
}
```

19. What is the difference between `std::forward_list` and `std::list` in C++?

Answer: `std::forward_list` is a singly linked list that allows forward traversal only, while `std::list` is a doubly

linked list that supports both forward and backward traversal. `std::forward_list` has lower memory overhead and faster insertion and deletion at the front compared to `std::list`.

20. How do you implement a smart pointer in C++?

Answer: A smart pointer can be implemented using templates and RAII principles to manage resource allocation and deallocation automatically. Example:
```cpp
template
class SmartPointer {
T* ptr;
public:
explicit SmartPointer(T* p = nullptr) : ptr(p) {}
~SmartPointer() { delete ptr; }
T& operator*() { return *ptr; }
T* operator->() { return ptr; }
};
```

21. What is the purpose of `std::launder` in C++17?

Answer: `std::launder` is used to obtain a pointer to an object created in storage that may have been reused, bypassing type aliasing rules. It ensures that the correct object is accessed in cases of object placement and memory manipulation. Example:
```cpp
int* p = new int(42);
new (p) int(84);
std::cout << *std::launder(p) << std::endl; // Output: 84
```

22. How do you use `std::shared_mutex` in C++17 for read-write locks?

Answer: `std::shared_mutex` allows multiple threads to read a shared resource concurrently, while exclusive write access is given to a single thread. Example:
```cpp
std::shared_mutex mtx;
void read() {
std::shared_lock lock(mtx);
// Read shared resource
}

void write() {
std::unique_lock lock(mtx);
// Write to shared resource
}
```

23. Explain the concept of RAII and how it applies to resource management in C++.

Answer: RAII (Resource Acquisition Is Initialization) is a programming idiom that binds resource management to object lifetime. Resources are acquired in constructors and released in destructors, ensuring proper cleanup and exception safety. Example:
```cpp
class File {
FILE* file;
public:
File(const char* filename) {
file = fopen(filename, "r");
}
~File() {
if (file) fclose(file);
}
};
```

24. How do you implement a singleton pattern in C++?

Answer: A singleton pattern ensures a class has only one instance and provides a global point of access to it. This can be implemented using a static member function and a private constructor. Example:
```cpp
class Singleton {
static Singleton* instance;
Singleton() {} // Private constructor
public:
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
```

25. What is the purpose of `std::scoped_lock` in C++17?

Answer: `std::scoped_lock` is a convenience wrapper for acquiring multiple locks in a deadlock-free manner. It locks multiple mutexes simultaneously and releases them when the `std::scoped_lock` goes out of scope. Example:
```cpp
std::mutex mtx1, mtx2;
void threadFunction() {
std::scoped_lock lock(mtx1, mtx2);
// Critical section
}
```
© 2024 parthakuchana.com