C++ Interview Questions and Answers
-
What is C++?
- Answer: C++ is a general-purpose, object-oriented programming (OOP) language that is an extension of the C programming language. It supports various programming paradigms, including procedural, object-oriented, and generic programming.
-
What are the basic building blocks of C++?
- Answer: Variables, data types, operators, control structures (if-else, loops), functions, classes, and objects.
-
Explain the difference between `int`, `float`, and `double` data types.
- Answer: `int` stores integers (whole numbers), `float` stores single-precision floating-point numbers (numbers with decimal points), and `double` stores double-precision floating-point numbers (more precise than `float`).
-
What is a pointer in C++?
- Answer: A pointer is a variable that holds the memory address of another variable. It's declared using the `*` symbol.
-
What is the purpose of the `new` and `delete` operators?
- Answer: `new` allocates memory dynamically at runtime, while `delete` deallocates dynamically allocated memory to prevent memory leaks.
-
Explain the concept of references in C++.
- Answer: A reference is an alias for an existing variable. It's declared using the `&` symbol. Once initialized, a reference cannot be changed to refer to a different variable.
-
What is a function in C++?
- Answer: A function is a block of code that performs a specific task. It can take arguments (input) and return a value (output).
-
What is function overloading?
- Answer: Function overloading allows multiple functions with the same name but different parameters (number, type, or order). The compiler determines which function to call based on the arguments provided.
-
What is operator overloading?
- Answer: Operator overloading allows defining the behavior of operators (e.g., +, -, *, /) for user-defined types (classes).
-
Explain the difference between `const` and `static` keywords.
- Answer: `const` indicates that a variable's value cannot be changed after initialization. `static` for a local variable means it retains its value between function calls; for a class member, it means there's only one copy shared among all objects of that class.
-
What are access specifiers in C++?
- Answer: Access specifiers (`public`, `private`, `protected`) control the accessibility of class members (data and functions) from outside the class.
-
What is inheritance in C++?
- Answer: Inheritance is a mechanism where a class (derived class) inherits properties and methods from another class (base class). It promotes code reusability and establishes an "is-a" relationship.
-
Explain different types of inheritance.
- Answer: Single inheritance (one base class), multiple inheritance (multiple base classes), multilevel inheritance (a derived class inherits from another derived class), hierarchical inheritance (multiple derived classes from one base class), hybrid inheritance (combination of multiple inheritance types).
-
What is polymorphism?
- Answer: Polymorphism allows objects of different classes to be treated as objects of a common type. It's often implemented using virtual functions and inheritance.
-
What is a virtual function?
- Answer: A virtual function is a member function declared using the `virtual` keyword. It allows dynamic dispatch, meaning the correct function to call is determined at runtime based on the object's type.
-
What is an abstract class?
- Answer: An abstract class is a class that cannot be instantiated. It serves as a base class for other classes and often contains pure virtual functions (functions declared with `= 0`).
-
What is a pure virtual function?
- Answer: A pure virtual function is a virtual function declared with `= 0`. It must be implemented in derived classes; otherwise, the derived class also becomes abstract.
-
What is an exception?
- Answer: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. C++ uses `try`, `catch`, and `throw` for exception handling.
-
Explain `try`, `catch`, and `throw` keywords.
- Answer: `try` encloses code that might throw an exception. `catch` handles exceptions of specific types. `throw` throws an exception object.
-
What is a template in C++?
- Answer: Templates allow writing generic code that can work with different data types without being rewritten for each type. They are used for functions and classes.
-
What is the Standard Template Library (STL)?
- Answer: The STL is a library of container classes (e.g., `vector`, `list`, `map`), algorithms, and iterators that provides reusable data structures and algorithms.
-
Explain the difference between `vector` and `array` in STL.
- Answer: `vector` is a dynamic array that can resize automatically, while `array` is a fixed-size array with a size known at compile time.
-
What is a smart pointer?
- Answer: A smart pointer is a class that acts like a pointer but automatically manages memory, preventing memory leaks. Examples include `unique_ptr`, `shared_ptr`, and `weak_ptr`.
-
Explain the difference between `unique_ptr`, `shared_ptr`, and `weak_ptr`.
- Answer: `unique_ptr` provides exclusive ownership of a dynamically allocated object. `shared_ptr` allows shared ownership among multiple pointers. `weak_ptr` is a non-owning pointer that can detect if the object it points to has been deleted.
-
What is RAII (Resource Acquisition Is Initialization)?
- Answer: RAII is a C++ programming idiom where resource management (like memory allocation) is tied to the object's lifetime. Resources are acquired when an object is created and released when it's destroyed.
-
What is the difference between a class and a struct in C++?
- Answer: The main difference is the default access specifier: `class` defaults to `private`, while `struct` defaults to `public`.
-
What is name mangling?
- Answer: Name mangling is the process by which the compiler transforms function and variable names into unique internal names to handle function overloading and linking.
-
What is a namespace?
- Answer: A namespace is a declarative region that provides a scope to prevent naming conflicts between identifiers.
-
What is the `this` pointer?
- Answer: The `this` pointer is a hidden pointer within a class's member functions that points to the current object instance.
-
What is the difference between `malloc()` and `new`?
- Answer: `malloc()` allocates raw memory without constructor calls, while `new` allocates memory and calls the constructor of the object being created.
-
What is the difference between `free()` and `delete`?
- Answer: `free()` deallocates memory allocated by `malloc()`, while `delete` deallocates memory allocated by `new` and calls the destructor of the object.
-
What are iterators in C++?
- Answer: Iterators are objects that act like pointers, allowing traversal of elements in containers (like vectors and lists) in a generic way.
-
Explain different types of iterators.
- Answer: Input iterators, output iterators, forward iterators, bidirectional iterators, random access iterators.
-
What is a lambda expression?
- Answer: A lambda expression is an anonymous function (a function without a name) that can be defined inline.
-
What is move semantics?
- 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 unnecessary copying of objects when they are returned from functions.
-
What is NRVO (Named Return Value Optimization)?
- Answer: NRVO is a compiler optimization similar to RVO, but it applies specifically when the returned object has a name (e.g., a local variable).
-
Explain the concept of perfect forwarding.
- Answer: Perfect forwarding is a technique used in templates to forward function arguments without making unnecessary copies or moves. It uses universal references.
-
What are variadic templates?
- Answer: Variadic templates allow functions and classes to accept a variable number of arguments of different types.
-
What is the difference between `std::copy` and `std::memcpy`?
- Answer: `std::copy` works with any type and uses iterators, while `std::memcpy` works only with raw bytes and uses pointers; `std::copy` is safer and more type-safe.
-
What is the difference between a left-value and a right-value?
- Answer: A left-value is an expression that can appear on the left side of an assignment operator (has a persistent location in memory). A right-value is an expression that cannot appear on the left side (e.g., a temporary object).
-
What is the role of the preprocessor in C++?
- Answer: The preprocessor processes the source code before compilation, handling directives like `#include`, `#define`, `#ifdef`, etc.
-
What are header files and why are they used?
- Answer: Header files contain declarations of functions, classes, and variables. They are included in source files using `#include` to make those declarations available.
-
What is the purpose of the `using namespace` directive?
- Answer: The `using namespace` directive makes identifiers from a specific namespace directly accessible without the namespace prefix.
-
What is a friend function?
- Answer: A friend function is a function declared as a friend of a class. It has access to the class's private and protected members.
-
What is a friend class?
- Answer: A friend class is a class declared as a friend of another class. All its member functions have access to the private and protected members of the befriended class.
-
Explain the difference between early and late binding.
- Answer: Early binding (static binding) resolves function calls at compile time. Late binding (dynamic binding) resolves function calls at runtime, using virtual functions.
-
What is the Standard Template Library (STL) algorithm `std::sort`?
- Answer: `std::sort` is a powerful algorithm that sorts a range of elements in ascending order using an efficient sorting algorithm (usually IntroSort).
-
What is the difference between `auto` and `decltype`?
- Answer: `auto` lets the compiler deduce the type of a variable from its initializer. `decltype` extracts the type of an expression without evaluating it.
-
What are smart pointers and why are they useful?
- Answer: Smart pointers automatically manage the lifetime of dynamically allocated objects, preventing memory leaks and dangling pointers.
-
How do you handle exceptions in C++?
- Answer: Exceptions are handled using `try`, `catch`, and `throw` blocks. The `try` block contains code that might throw an exception; `catch` blocks handle different exception types; `throw` throws an exception object.
-
What is the role of a destructor?
- Answer: A destructor is a special member function of a class that is called automatically when an object goes out of scope or is explicitly deleted using `delete`. It's used to release resources held by the object.
-
Explain the concept of copy constructors.
- Answer: A copy constructor is a special member function that creates a copy of an existing object. It's automatically called when an object is initialized from another object of the same type.
-
Explain the concept of assignment operators.
- Answer: An assignment operator (usually `=`) is a special member function that assigns the values of one object to another object of the same type. It's called when using the assignment operator between two objects.
-
What is the rule of five/zero?
- Answer: The rule of five (or zero) describes when you need to define the destructor, copy constructor, copy assignment operator, move constructor, and move assignment operator. If you define one, you often need the others to ensure proper resource management. The rule of zero advocates for avoiding these explicit definitions where possible by using smart pointers and value semantics.
-
What is a container in C++?
- Answer: A container is a data structure that stores a collection of objects. The STL provides many standard containers, such as `vector`, `list`, `map`, `set`, etc.
-
What is an iterator in C++?
- Answer: An iterator is an object that acts like a pointer, allowing you to traverse the elements of a container in a generic way.
-
What is the difference between `std::vector` and `std::list`?
- Answer: `std::vector` provides random access to elements with contiguous storage, while `std::list` provides only sequential access with non-contiguous storage. `vector` is generally faster for element access, while `list` is faster for insertions and deletions in the middle.
-
What is the difference between `std::map` and `std::unordered_map`?
- Answer: `std::map` stores elements in a sorted order based on the key, providing logarithmic time complexity for search, insertion, and deletion. `std::unordered_map` uses a hash table, providing average constant time complexity for these operations but no guaranteed order.
-
What is a function object (functor)?
- Answer: A function object is a class that overloads the `operator()` allowing it to be called like a function.
-
What is the difference between pass by value, pass by reference, and pass by pointer?
- Answer: Pass by value creates a copy of the argument. Pass by reference passes a reference to the argument, avoiding copying. Pass by pointer passes a pointer to the argument's memory location.
-
What is a memory leak?
- Answer: A memory leak occurs when dynamically allocated memory is not freed, leading to gradual exhaustion of available memory.
-
What is a dangling pointer?
- Answer: A dangling pointer points to memory that has been deallocated or freed.
-
What is the difference between const correctness and immutability?
- Answer: Const correctness is about preventing accidental modification of data through the use of the `const` keyword. Immutability means that an object cannot be changed after it's created.
-
Explain the concept of compile-time polymorphism.
- Answer: Compile-time polymorphism (static polymorphism) is achieved through function overloading and operator overloading. The compiler determines which function to call at compile time.
-
Explain the concept of runtime polymorphism.
- Answer: Runtime polymorphism (dynamic polymorphism) is achieved through virtual functions and inheritance. The correct function to call is determined at runtime based on the object's type.
-
What is the difference between a class and an object?
- Answer: A class is a blueprint for creating objects. An object is an instance of a class.
-
What is the difference between static and dynamic linking?
- Answer: Static linking incorporates library code directly into the executable at compile time. Dynamic linking links the library at runtime.
-
What is the difference between a declaration and a definition?
- Answer: A declaration introduces a name and its type to the compiler without allocating memory. A definition allocates memory and provides the implementation.
-
What is the role of the linker?
- Answer: The linker combines object files and libraries to create an executable file.
-
What are the different storage classes in C++?
- Answer: `auto`, `register`, `static`, `extern`, `mutable`.
-
What is a volatile keyword?
- Answer: The `volatile` keyword tells the compiler that a variable's value might be changed unexpectedly (e.g., by hardware or another thread), preventing optimizations that might assume the variable's value remains constant.
-
What is the Standard Template Library (STL) algorithm `std::find`?
- Answer: `std::find` searches for a specific value within a range of elements and returns an iterator to the first occurrence if found, otherwise returns an iterator to the end of the range.
-
What is the Standard Template Library (STL) algorithm `std::transform`?
- Answer: `std::transform` applies a given function to each element of a range and stores the results in another range.
-
What is the difference between `sizeof` and `strlen`?
- Answer: `sizeof` is a compile-time operator that gives the size of a data type or variable in bytes. `strlen` is a runtime function that gives the length of a null-terminated C-style string.
-
What are the different ways to initialize a `std::vector`?
- Answer: Several ways exist, including default construction, specifying size, specifying size and value, and using an initializer list.
-
How do you implement a singly linked list in C++?
- Answer: A singly linked list consists of nodes, where each node points to the next node in the sequence. You'd need a Node class with data and a pointer to the next node, and a LinkedList class to manage the list.
-
How do you implement a doubly linked list in C++?
- Answer: Similar to a singly linked list but each node has pointers to both the next and previous nodes.
-
How do you implement a binary search tree in C++?
- Answer: A binary search tree (BST) is a tree data structure where the left subtree contains nodes with keys less than the root node's key, and the right subtree contains nodes with keys greater than the root node's key. Recursive insertion and searching are common implementations.
-
What is a stack in C++?
- Answer: A stack is a LIFO (Last-In, First-Out) data structure. Elements are added (pushed) and removed (popped) from the top.
-
What is a queue in C++?
- Answer: A queue is a FIFO (First-In, First-Out) data structure. Elements are added (enqueued) at the rear and removed (dequeued) from the front.
Thank you for reading our blog post on 'C++ Interview Questions and Answers'.We hope you found it informative and useful.Stay tuned for more insightful content!