C ++ interview questions and answers
List of 100 C++ interview questions and answers, categorized by topic. These questions are frequently asked in technical interviews to assess a candidate’s understanding of C++ concepts.
1. Basics of C++
What is C++?
C++ is a high-level programming language developed by Bjarne Stroustrup as an extension of the C language. It supports object-oriented, procedural, and generic programming paradigms.
What are the major differences between C and C++?
C is a procedural language, while C++ supports both procedural and object-oriented programming. C++ introduces classes, objects, inheritance, and polymorphism.
What are classes and objects in C++?
A class is a blueprint for creating objects (instances). An object is an instance of a class.
What is a namespace in C++?
A namespace is used to avoid name collisions by grouping logically related identifiers under a unique name.
What is the role of the main() function in C++?
The main() function is the entry point of a C++ program, where execution starts.
What is the difference between cin and cout?
cin is used for input (from standard input, usually the keyboard), while cout is used for output (to standard output, usually the screen).
What is a reference variable in C++?
A reference is an alias for another variable. It is created using the & symbol and must be initialized when declared.
What are pointers in C++?
A pointer is a variable that stores the address of another variable. Pointers are declared using the * operator.
What is the difference between new and malloc()?
new is a C++ operator that initializes objects and returns a pointer to the allocated memory, whereas malloc() is a C function that allocates memory without initialization.
What is a destructor in C++?
A destructor is a member function of a class that is executed automatically when an object is destroyed, used to release resources.
2. Object-Oriented Programming
What is Object-Oriented Programming (OOP)?
OOP is a programming paradigm based on the concept of objects which contain data and methods.
What are the four pillars of OOP?
Encapsulation, Abstraction, Inheritance, and Polymorphism.
What is encapsulation?
Encapsulation is the bundling of data and methods into a single unit (class) and restricting access to some of the object’s components.
What is inheritance?
Inheritance is a mechanism where one class acquires the properties and behavior (methods) of another class.
What is polymorphism?
Polymorphism allows a function or object to take on many forms, mainly through function overloading and overriding.
What is function overloading?
Function overloading allows multiple functions with the same name but different parameter lists.
What is operator overloading?
Operator overloading allows C++ operators to be redefined for user-defined types.
What is a virtual function?
A virtual function is a function declared in a base class that can be overridden in derived classes to achieve runtime polymorphism.
What is the purpose of the this pointer in C++?
The this pointer points to the object that invokes the member function and allows access to its members.
What is an abstract class?
An abstract class is a class that cannot be instantiated and must have at least one pure virtual function.
3. Memory Management
What is dynamic memory allocation in C++?
Dynamic memory allocation allows memory to be allocated at runtime using new and delete.
What is the difference between new and delete?
new allocates memory on the heap, while delete deallocates the memory.
What are the types of memory used in C++?
Stack memory (for local variables) and heap memory (for dynamically allocated objects).
What is a memory leak?
A memory leak occurs when dynamically allocated memory is not deallocated, leading to wasted memory.
What is RAII (Resource Acquisition Is Initialization)?
RAII is a C++ programming idiom where resources (memory, file handles) are tied to the lifetime of objects, ensuring proper cleanup.
What is a smart pointer?
A smart pointer is a C++ object that acts like a pointer but manages the memory automatically, reducing the risk of memory leaks (e.g., std::unique_ptr, std::shared_ptr).
What is the use of std::unique_ptr?
std::unique_ptr is a smart pointer that retains sole ownership of an object and deletes the object when the pointer goes out of scope.
What is the difference between std::unique_ptr and std::shared_ptr?
std::unique_ptr ensures unique ownership of an object, while std::shared_ptr allows multiple pointers to share ownership of an object, with automatic deletion when the last pointer is destroyed.
What is std::weak_ptr?
std::weak_ptr is a smart pointer that holds a non-owning reference to an object managed by std::shared_ptr.
What is a dangling pointer?
A dangling pointer refers to a memory location that has already been freed.
4. Constructors and Destructors
What is a constructor in C++?
A constructor is a special member function that initializes objects of a class.
What are the types of constructors?
Default constructor, parameterized constructor, copy constructor, and move constructor.
What is a copy constructor?
A copy constructor creates a new object as a copy of an existing object.
What is a move constructor?
A move constructor transfers resources from a temporary object to a new object, leaving the temporary object in a valid but unspecified state.
What is constructor overloading?
Constructor overloading allows a class to have multiple constructors with different parameter lists.
What is a default constructor?
A default constructor is a constructor that takes no arguments or has default values for all its parameters.
What is a destructor?
A destructor is used to clean up resources when an object goes out of scope or is explicitly deleted.
Can a constructor be private?
Yes, constructors can be private, often used in singleton pattern implementations.
Can we call the constructor explicitly?
Yes, constructors can be called explicitly, but doing so directly is uncommon.
What happens if a class does not have a destructor?
If a class does not define a destructor, the compiler generates a default destructor, which does not perform any special resource cleanup.
5. Inheritance
What is single inheritance?
Single inheritance involves one class inheriting from a single base class.
What is multiple inheritance?
Multiple inheritance is when a class inherits from more than one base class.
What is multilevel inheritance?
Multilevel inheritance refers to a class derived from a class that is already derived from another class.
What is hierarchical inheritance?
Hierarchical inheritance is when multiple classes are derived from a single base class.
What is hybrid inheritance?
Hybrid inheritance is a combination of multiple and multilevel inheritance.
What is the protected access specifier?
protected members are accessible within the class and by derived classes, but not by other external code.
What is the order of constructor calls in inheritance?
In a derived class, the base class constructor is called first, followed by the derived class constructor.
What is virtual inheritance?
Virtual inheritance is used to solve the diamond problem in multiple inheritance by ensuring that only one instance of the common base class is inherited.
What is the diamond problem in inheritance?
The diamond problem occurs when two classes inherit from a common base class, and a third class inherits from these two classes, leading to ambiguity about which base class constructor to call.
What is the difference between public, private, and protected inheritance?
Public inheritance makes the public members of the base class public in the derived class, private inheritance makes them private, and protected inheritance makes them protected.
6. Polymorphism
What is static polymorphism?
Static polymorphism is achieved at compile time, typically through function overloading or operator overloading.
What is dynamic polymorphism?
Dynamic polymorphism is achieved at runtime, usually through virtual functions and function overriding.
What is function overriding?
Function overriding occurs when a derived class provides a specific implementation of a function that is already defined in its base class.
What is a pure virtual function?
A pure virtual function is a function with no definition in the base class and must be overridden by derived classes.
What is virtual inheritance?
Virtual inheritance ensures that only one copy of a base class’s members are inherited by the grandchild class in multiple inheritance.
Can we override private virtual functions?
No, private virtual functions cannot be overridden directly by derived classes as they are inaccessible.
Can we have a virtual constructor?
No, constructors cannot be virtual in C++ because they are responsible for object creation, and the virtual mechanism requires an existing object.
What is final in C++?
final is used to prevent further inheritance of a class or overriding of a virtual function.
What is the override keyword in C++?
override is used to explicitly state that a function is meant to override a base class function, helping catch errors at compile time.
What is covariance in return types?
Covariance allows a derived class function to return a pointer or reference to a derived class type when overriding a base class function that returns a pointer or reference to the base class.
7. Templates and STL
What is a template in C++?
A template is a feature that allows functions and classes to operate with generic types.
What is the difference between a function template and a class template?
A function template defines a template for a function, whereas a class template defines a template for an entire class.
What is template specialization?
Template specialization allows for a specific implementation of a template for a particular type or set of types.
What is the Standard Template Library (STL)?
The STL is a collection of classes and functions in C++ for common data structures (like vectors, lists) and algorithms.
What are the components of STL?
The STL consists of containers, iterators, and algorithms.
What are containers in STL?
Containers are data structures that store objects and data (e.g., vector, list, deque, map, set).
What is a vector in STL?
A vector is a dynamic array that can resize itself automatically when elements are added or removed.
What is a map in STL?
A map is an associative container that stores key-value pairs, with unique keys for each value.
What is the difference between set and map in STL?
A set contains unique elements, while a map contains key-value pairs with unique keys.
What is an iterator in C++?
An iterator is an object that enables traversal over the elements of a container.
8. Exception Handling
What is exception handling in C++?
Exception handling is a mechanism to handle runtime errors using try, catch, and throw blocks.
How do you throw an exception in C++?
An exception is thrown using the throw keyword followed by an exception object or value.
What is a try-catch block in C++?
The try block contains code that may throw an exception, and the catch block handles the exception.
What is the purpose of the throw keyword?
The throw keyword is used to signal that an exception has occurred.
What is a std::exception in C++?
std::exception is the base class for all standard exceptions in C++.
What is the noexcept keyword in C++?
noexcept is used to specify that a function does not throw exceptions.
What is a try block?
A try block contains code that may potentially cause an exception.
Can a constructor throw an exception?
Yes, constructors can throw exceptions if something goes wrong during object creation.
What is stack unwinding?
Stack unwinding is the process of cleaning up the stack when an exception is thrown, as the program looks for a matching catch block.
What is the use of std::bad_alloc?
std::bad_alloc is an exception thrown when memory allocation fails, typically when using new.
9. Advanced C++
What are function pointers in C++?
Function pointers are pointers that point to the address of a function, allowing dynamic invocation of functions.
What is the difference between struct and class in C++?
The only difference is the default access specifier: struct has public members by default, while class has private members by default.
What is a lambda expression in C++?
A lambda expression is an anonymous function that can capture variables from its surrounding scope and is useful for short, inline function definitions.
What are move semantics in C++?
Move semantics allow resources to be transferred from one object to another, avoiding unnecessary copying and enhancing performance.
What is the rule of three?
The rule of three states that if a class defines one of the following, it should define all three: destructor, copy constructor, and copy assignment operator.
What is the rule of five?
The rule of five extends the rule of three by including the move constructor and move assignment operator.
What is the difference between std::vector and std::array?
std::vector is dynamic and can change size, while std::array has a fixed size and cannot resize.
What are regular expressions in C++?
Regular expressions are patterns used to match character combinations in strings, supported by the <regex> library in C++.
What is the use of std::thread in C++?
std::thread is used to create and manage threads for concurrent execution of code in C++.
What is the decltype keyword in C++?
decltype inspects the type of an expression without evaluating it and is used for type deduction.
10. Miscellaneous
What is a friend function in C++?
A friend function can access the private and protected members of a class, even though it is not a member of the class.
What is a mutable keyword in C++?
mutable allows a member of a constant object to be modified, breaking the usual rule that const objects cannot change.
What is a preprocessor in C++?
The preprocessor processes directives before the actual compilation of code, such as #include and #define.
What are macros in C++?
Macros are defined using #define and represent code fragments that are replaced by the preprocessor.
What is type casting in C++?
Type casting is converting one data type to another, such as using static_cast, dynamic_cast, const_cast, and reinterpret_cast.
What is the sizeof operator?
sizeof returns the size, in bytes, of a type or variable.
What is the difference between sizeof() and strlen()?
sizeof() gives the size of a type or object, while strlen() is used for strings and returns the length of the string excluding the null terminator.
What is the difference between shallow copy and deep copy?
A shallow copy duplicates the reference to an object, while a deep copy duplicates the entire object and all objects it references.
What is the difference between a macro and an inline function?
A macro is processed by the preprocessor, whereas an inline function is a function that the compiler attempts to expand at the point of call to reduce overhead.
What is a volatile keyword in C++?
volatile tells the compiler that a variable can be changed unexpectedly, preventing optimization for certain scenarios like hardware access.
No comments:
Post a Comment