C++ Interview Questions and Answers for 2 years experience
-
What is the difference between `malloc()` and `new`?
- Answer: `malloc()` allocates raw memory and returns a void pointer. You need to cast it to the appropriate pointer type and manually manage its deallocation using `free()`. `new` allocates memory and automatically calls the constructor of the object being created. It also handles deallocation using `delete` (or `delete[]` for arrays), which automatically calls the destructor. `new` is type-safe, while `malloc()` is not.
-
Explain the concept of polymorphism in C++.
- Answer: Polymorphism allows objects of different classes to be treated as objects of a common type. This is achieved through virtual functions and inheritance. A virtual function allows derived classes to provide their own implementations of a function defined in the base class. This enables you to call the same function on objects of different classes, and the correct implementation will be executed based on the object's actual type at runtime.
-
What is a virtual function in C++?
- Answer: A virtual function is a member function of a base class that is declared using the `virtual` keyword. It allows derived classes to override the base class implementation, enabling runtime polymorphism. When a virtual function is called through a pointer or reference to the base class, the correct overridden function in the derived class is executed, determined at runtime.
-
What is the difference between `const` and `static` keywords?
- Answer: `const` indicates that a variable's value cannot be changed after initialization. `static`, when applied to a variable, makes it local to a single instance of a function or class, maintaining its value between calls. When applied to a member variable of a class, it creates a single copy of the variable shared across all instances of the class. When applied to a member function of a class, it makes it a class-level function that doesn't operate on a specific object instance.
-
What is RAII (Resource Acquisition Is Initialization)?
- Answer: RAII is a programming idiom where resource management (e.g., memory, file handles, network connections) is tied to the object's lifetime. Resources are acquired in the constructor and released in the destructor, ensuring resources are always released, even in exceptional situations.
-
Explain the difference between a class and a struct in C++.
- Answer: The primary difference is the default access specifier: `class` defaults to `private` member access, while `struct` defaults to `public`. Functionally, they are nearly identical.
-
What are smart pointers in C++? Name some examples.
- Answer: Smart pointers are classes that act like pointers but automatically manage the memory they point to, preventing memory leaks. Examples include `unique_ptr`, `shared_ptr`, and `weak_ptr`.
-
What is the role of a destructor?
- Answer: A destructor is a special member function called automatically when an object goes out of scope or is explicitly deleted. Its purpose is to release resources held by the object, such as dynamically allocated memory or file handles.
-
Explain operator overloading.
- Answer: Operator overloading allows you to redefine the behavior of operators (e.g., +, -, *, /, ==) for user-defined types. This enables more intuitive code by allowing operators to work with custom objects.
-
What is a template in C++?
- Answer: A template is a blueprint for creating generic classes or functions. It allows you to write code that can work with various data types without needing to write separate versions for each type.
-
What is exception handling in C++?
- Answer: Exception handling provides a mechanism to gracefully handle runtime errors. It involves using `try`, `catch`, and `throw` blocks to isolate error handling code, preventing program crashes.
-
Explain the difference between `throw` and `catch`.
- Answer: `throw` is used to signal an exception, interrupting the normal flow of execution. `catch` is used to handle exceptions; it specifies the type of exception it can handle and executes code to recover from the error.
-
What is the Standard Template Library (STL)?
- Answer: The STL is a set of container classes, algorithms, and iterators that provide ready-to-use data structures and algorithms, promoting code reusability and efficiency.
-
Name some common STL containers.
- Answer: `vector`, `list`, `deque`, `set`, `map`, `unordered_set`, `unordered_map` are some common STL containers.
-
What is the difference between a vector and a list in STL?
- Answer: `vector` provides dynamic array functionality with contiguous memory allocation, offering fast random access but slow insertion/deletion in the middle. `list` is a doubly linked list, allowing fast insertion/deletion anywhere but slower random access.
-
What are iterators in STL?
- Answer: Iterators are objects that act like pointers, allowing you to traverse elements in containers. They provide a uniform interface for accessing elements regardless of the container type.
-
Explain inheritance in C++.
- Answer: Inheritance is a mechanism where a class (derived class) inherits properties and behaviors from another class (base class). This promotes code reuse and establishes an "is-a" relationship between classes.
-
What are the different types of inheritance in C++?
- Answer: Public, protected, and private inheritance. They control the access level of the inherited members in the derived class.
-
What is a namespace in C++?
- Answer: Namespaces provide a way to organize code and prevent naming conflicts. They group related identifiers under a unique name, preventing collisions with identifiers in other parts of the code.
-
What is the role of a constructor?
- Answer: A constructor is a special member function called automatically when an object is created. Its purpose is to initialize the object's member variables.
-
What is the difference between a copy constructor and an assignment operator?
- Answer: A copy constructor creates a new object as a copy of an existing object. The assignment operator (=) assigns the values of one object to another existing object.
-
Explain the concept of function overloading.
- Answer: Function overloading allows you to define multiple functions with the same name but different parameter lists (number, type, or order). The compiler determines which function to call based on the arguments provided.
-
What is a friend function in C++?
- Answer: A friend function is a function that is not a member of a class but has access to the class's private and protected members. It is declared using the `friend` keyword within the class definition.
-
What is a pure virtual function?
- Answer: A pure virtual function is a virtual function declared with the assignment `= 0`. A class containing a pure virtual function is an abstract class and cannot be instantiated. Derived classes must provide an implementation for the pure virtual function.
-
What is an abstract class?
- Answer: An abstract class is a class that cannot be instantiated directly. It serves as a base class for other classes and contains at least one pure virtual function.
-
Explain dynamic and static binding.
- Answer: Static binding (or early binding) resolves function calls at compile time. Dynamic binding (or late binding) resolves function calls at runtime, typically using virtual functions.
-
What is the difference between `std::string` and C-style strings?
- Answer: `std::string` is a class that provides a more robust and convenient way to handle strings compared to C-style strings (null-terminated character arrays). `std::string` automatically manages memory and provides various helpful member functions.
-
What are some common C++ debugging techniques?
- Answer: Using a debugger (like gdb or Visual Studio debugger), inserting print statements (`std::cout`), using logging libraries, and employing assertions (`assert()`).
-
Explain the concept of memory leaks.
- Answer: A memory leak occurs when dynamically allocated memory is no longer needed but not released, leading to gradual depletion of available memory.
-
How can you prevent memory leaks?
- Answer: Using smart pointers, ensuring proper deallocation using `delete` or `delete[]`, and avoiding manual memory management whenever possible.
-
What is the difference between pre-increment and post-increment operators?
- Answer: Pre-increment (++i) increments the variable before its value is used. Post-increment (i++) increments the variable after its value is used.
-
What is a lambda expression in C++?
- Answer: A lambda expression is an anonymous function (a function without a name) that can be defined inline where it's used. It's often used with STL algorithms.
-
Explain the use of `auto` keyword.
- Answer: `auto` allows the compiler to deduce the type of a variable from its initializer, reducing code verbosity and improving readability.
-
What is move semantics in C++?
- 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.
-
What is RVO (Return Value Optimization)?
- Answer: RVO is a compiler optimization that avoids creating a temporary object when returning a local object by value. The compiler directly constructs the returned object in the caller's memory location.
-
What is NRVO (Named Return Value Optimization)?
- Answer: NRVO is a compiler optimization similar to RVO, but it applies when the returned object is named (not anonymous). It avoids unnecessary copying when returning a local object by value.
-
Explain the concept of copy elision.
- Answer: Copy elision is a compiler optimization that eliminates unnecessary copying of objects. It's a broader term that encompasses both RVO and NRVO.
-
What is perfect forwarding?
- Answer: Perfect forwarding is a technique used to forward arguments to another function while preserving their value category (lvalue or rvalue). It's crucial for implementing generic functions that can handle both lvalues and rvalues correctly.
-
What are the different types of memory allocation in C++?
- Answer: Static, automatic (stack), and dynamic (heap) memory allocation.
-
Explain the difference between stack and heap memory.
- Answer: Stack memory is automatically managed; it's fast but has limited size. Heap memory requires explicit allocation and deallocation; it's slower but has a larger capacity.
-
What is the difference between `std::cout` and `std::cerr`?
- Answer: `std::cout` is the standard output stream, typically connected to the console. `std::cerr` is the standard error stream, also usually connected to the console but is unbuffered, ensuring error messages are displayed immediately.
-
What are some common design patterns in C++?
- Answer: Singleton, Factory, Observer, Strategy, Command, Decorator, Adapter are some examples.
-
What is the difference between single inheritance and multiple inheritance?
- Answer: Single inheritance: A class inherits from only one base class. Multiple inheritance: A class inherits from multiple base classes.
-
What are the advantages and disadvantages of multiple inheritance?
- Answer: Advantages: Increased code reusability. Disadvantages: Increased complexity, potential for ambiguity (diamond problem).
-
How do you handle exceptions thrown from within a destructor?
- Answer: Avoid throwing exceptions from destructors. If an exception is unavoidable, it's generally best to log the error and continue cleanup; terminating the program at this stage can be dangerous.
-
What is a dangling pointer?
- Answer: A dangling pointer is a pointer that points to memory that has been deallocated or freed. Accessing it can lead to undefined behavior or crashes.
-
How do you handle dangling pointers?
- Answer: Using smart pointers, careful memory management, nulling out pointers after deallocation, and good coding practices help prevent dangling pointers.
-
What is the purpose of the `volatile` keyword?
- Answer: The `volatile` keyword tells the compiler that a variable's value can be changed by external factors (e.g., hardware, other threads) that the compiler cannot predict. It prevents compiler optimizations that might assume the variable's value is constant.
-
What is the difference between `const int *ptr` and `int * const ptr`?
- Answer: `const int *ptr`: The value pointed to by `ptr` is constant. `int * const ptr`: The pointer itself is constant (cannot be reassigned to point to a different address).
-
What is the role of the preprocessor in C++?
- Answer: The preprocessor handles directives like `#include`, `#define`, `#ifdef`, etc. before compilation, performing text-based transformations on the source code.
-
What is the difference between `#include
` and `#include "iostream"`? - Answer: `#include
` searches for the header file in standard system directories. `#include "iostream"` first searches in the current directory before looking in standard system directories.
- Answer: `#include
Thank you for reading our blog post on 'C++ Interview Questions and Answers for 2 years experience'.We hope you found it informative and useful.Stay tuned for more insightful content!