C++ Interview Questions and Answers for 7 years experience
-
What is the difference between a pointer and a reference in C++?
- Answer: Pointers are variables that hold memory addresses, while references are aliases for existing variables. Pointers can be reassigned to point to different memory locations, while references must be initialized at declaration and cannot be changed to refer to another variable. Pointers can be NULL, while references cannot be NULL. Pointers require dereferencing (*) to access the value they point to, while references can be used directly.
-
Explain the concept of polymorphism in C++. Give examples.
- Answer: Polymorphism allows objects of different classes to be treated as objects of a common type. This is achieved through virtual functions and inheritance. For example, a base class "Animal" might have a virtual function "makeSound()". Derived classes like "Dog" and "Cat" can override this function to provide their specific implementations. A function taking an "Animal*" pointer can then call `makeSound()` on any Animal object, and the correct version will be executed at runtime (dynamic polymorphism).
-
What are smart pointers in C++ and why are they important? Name at least three types.
- Answer: Smart pointers are classes that act like pointers but automatically manage the memory they point to, preventing memory leaks. They automatically delete the pointed-to object when it's no longer needed. Three common types are: `unique_ptr` (exclusive ownership), `shared_ptr` (shared ownership), and `weak_ptr` (non-owning observer).
-
Explain the difference between `const int* ptr` and `int* const ptr`.
- Answer: `const int* ptr` declares a pointer to a constant integer. The integer value cannot be changed through this pointer, but the pointer itself can be reassigned to point to a different integer. `int* const ptr` declares a constant pointer to an integer. The pointer itself cannot be reassigned, but the integer value it points to can be changed.
-
What is the RAII (Resource Acquisition Is Initialization) principle?
- Answer: RAII is a programming idiom where resource allocation is tied to object initialization, and resource deallocation is tied to object destruction. This ensures resources are always released properly, even in the face of exceptions. Smart pointers are a prime example of RAII.
-
Explain the concept of operator overloading in C++.
- Answer: Operator overloading allows you to redefine the behavior of operators (like +, -, *, /, etc.) for user-defined types. This allows for more intuitive and readable code when working with custom classes. For example, you could overload the + operator to add two objects of your custom class.
-
What are virtual functions and abstract classes in C++?
- Answer: Virtual functions are member functions declared with the `virtual` keyword in a base class. They allow for dynamic dispatch, meaning the correct function implementation is chosen at runtime based on the object's type. Abstract classes are classes containing at least one pure virtual function (declared as `virtual void myFunc() = 0;`). Abstract classes cannot be instantiated; they serve as blueprints for derived classes.
-
What is the difference between a class and a struct in C++?
- Answer: In C++, the difference between `class` and `struct` is primarily a matter of default access specifiers. Members of a `class` are private by default, while members of a `struct` are public by default. Functionally, they are otherwise identical.
-
Explain the concept of templates in C++.
- Answer: Templates allow you to write generic code that can work with different data types without being rewritten for each type. Function templates operate on various data types, while class templates create generic classes that can be instantiated with different types.
-
What are exceptions in C++? How do you handle them?
- Answer: Exceptions are events that disrupt the normal flow of a program's execution. They are handled using `try`, `catch`, and `throw` blocks. A `try` block encloses code that might throw an exception. `catch` blocks handle specific exception types. `throw` statements initiate exceptions.
-
How do you achieve exception safety in your C++ code?
- Answer: Exception safety is achieved through careful resource management (RAII), using smart pointers to manage memory and other resources, and ensuring that your code either completes its operation successfully or leaves no trace of having started (strong exception guarantee). The use of techniques like the copy-and-swap idiom can help.
-
Explain the differences between `std::vector`, `std::list`, and `std::deque` in the STL.
- Answer: `std::vector` provides dynamic array functionality with contiguous memory allocation. `std::list` is a doubly linked list, offering efficient insertion and deletion but slower random access. `std::deque` is a double-ended queue, providing efficient insertion and deletion at both ends and relatively fast random access.
-
Describe the concept of move semantics in C++11 and later.
- Answer: Move semantics provide a way to efficiently transfer ownership of resources from one object to another without copying. This is achieved using rvalue references and move constructors/assignment operators. It avoids unnecessary copying, leading to performance improvements, particularly for large objects.
-
What is the purpose of the `volatile` keyword?
- Answer: The `volatile` keyword indicates that a variable's value might be changed by factors outside the control of the compiler, such as hardware or another thread. The compiler will not optimize away accesses to volatile variables.
-
Explain the difference between inheritance and composition.
- Answer: Inheritance creates an "is-a" relationship between classes, while composition creates a "has-a" relationship. Inheritance is a stronger coupling than composition, making changes in the base class more impactful on derived classes. Composition generally offers more flexibility and maintainability.
-
What are lambda expressions in C++?
- Answer: Lambda expressions are anonymous functions, often used for short, simple operations, such as callbacks or function arguments. They allow you to create functions inline, avoiding the need for separate function definitions.
-
How does the C++ Standard Template Library (STL) work?
- Answer: The STL provides a collection of generic algorithms and data structures that can be used with different data types. It leverages templates extensively, enabling code reusability. Key components include containers (like `vector`, `list`, `map`), iterators, and algorithms.
-
What are some common design patterns used in C++?
- Answer: Many design patterns are applicable in C++, including Singleton, Factory, Observer, Strategy, Command, and more. These provide reusable solutions to common software design problems.
-
Explain the concept of a mutex in C++ multithreading.
- Answer: A mutex (mutual exclusion) is a synchronization primitive that prevents multiple threads from accessing a shared resource simultaneously. It ensures thread safety by allowing only one thread to hold the mutex at any given time.
Thank you for reading our blog post on 'C++ Interview Questions and Answers for 7 years experience'.We hope you found it informative and useful.Stay tuned for more insightful content!