Interview Questions
A collection of C++ interview questions ranging from fundamentals to more advanced topics, with concise, accurate answers. Good both for interview preparation and as a self-check across the concepts covered in this tutorial.
1. What is the difference between a pointer and a reference?
nullptr. A reference is an alias for an existing variable — it must be bound to something at creation, can never be reseated to refer to a different object, and cannot be null. Prefer references when null isn't a valid state and rebinding is never needed; use pointers (ideally smart pointers) when optionality or reseating is required.2. Explain RAII.
RAII (Resource Acquisition Is Initialization) ties a resource's lifetime to an object's lifetime: acquiring the resource in the constructor and releasing it in the destructor. Because C++ guarantees destructors run when an object goes out of scope — even during exception-driven stack unwinding — RAII gives automatic, exception-safe cleanup for memory, files, locks, and sockets, with no manual "remember to release this" step.
3. What is the Rule of Three/Five (and Rule of Zero)?
If a class needs a custom destructor, copy constructor, or copy assignment operator, it almost certainly needs all three (Rule of Three) — typically because it manages a raw resource. The Rule of Five extends this to include the move constructor and move assignment operator for efficient transfers. The Rule of Zero says the best outcome is needing none of the five, by composing the class entirely out of RAII members (std::vector, std::unique_ptr) that already manage themselves correctly.
4. What's the difference between stack and heap memory?
Stack memory is managed automatically in LIFO order as functions are called and return — allocation and deallocation are fast, but lifetime is tied to scope and size is limited. Heap memory is allocated on demand (new, or indirectly via containers/smart pointers) and persists until explicitly freed, offering flexible size and lifetime at the cost of slower allocation and the responsibility to free it correctly.
5. What is a virtual function and how does it work?
A virtual function is declared in a base class and can be overridden in derived classes; calling it through a base pointer or reference invokes the derived class's version at runtime, not the base version. The compiler implements this with a vtable — a per-class table of function pointers — and each polymorphic object holds a hidden pointer to its class's vtable, which is what makes runtime dispatch possible.
6. Explain smart pointers and their types.
std::unique_ptr represents sole, non-shared ownership and cannot be copied, only moved. std::shared_ptr allows multiple owners via reference counting, destroying the object once the last owner is gone. std::weak_ptr observes a shared_ptr-owned object without contributing to its reference count, avoiding reference cycles.7. What is undefined behavior? Give an example.
int arr[3]; arr[3] = 1; compiles and may run without crashing, yet it has already corrupted memory it doesn't own.8. What's the difference between struct and class?
In C++, they are nearly identical — both can have constructors, methods, and inherit from other types. The only real differences are the default access level (public for struct, private for class) and default inheritance visibility (public vs private). By convention, struct is used for simple data aggregates with no invariants to enforce, and class for types with behavior and encapsulated invariants.
9. What is a memory leak and how do you prevent one?
new/delete altogether — use smart pointers and STL containers, which free their memory automatically via RAII when they go out of scope, regardless of early returns or thrown exceptions.10. Explain move semantics.
T&&). A move constructor "steals" the internal pointer/state from the source object and leaves it in a valid but empty state, avoiding an expensive deep copy — critical for returning large objects from functions or inserting into containers efficiently.11. What is the difference between `==` and using `std::string::compare`?
== on two std::string objects returns a simple boolean for equality and is the more idiomatic, readable choice for equality checks. .compare() returns an int (negative, zero, or positive) indicating lexicographic ordering, useful when you need to know which string is "less than" the other, not just whether they're equal.12. What does the `const` keyword mean when applied to a member function?
const member function promises not to modify the object's observable state, and can be called on const instances of the class. It's enforced by the compiler — attempting to modify a non-mutable member inside a const function is a compile error.13. What is function overloading vs. overriding?
Overloading is defining multiple functions with the same name but different parameter lists in the same scope, resolved at compile time based on the arguments passed. Overriding is a derived class replacing a base class's virtual function with the same signature, resolved at runtime based on the object's actual type.
14. Why should you catch exceptions by reference rather than by value?
std::exception, any derived-class-specific information is sliced off. Catching by const& avoids the copy and preserves the object's full, actual runtime type for polymorphic behavior like what().15. What is a dangling pointer?
deleted. Dereferencing it is undefined behavior, even though the pointer itself looks perfectly valid.16. What is the difference between `std::vector` and `std::array`?
std::array<T, N> has a fixed size known at compile time, stored inline (often on the stack) with no heap allocation. std::vector<T> can grow and shrink at runtime, storing its elements in dynamically allocated heap memory that it manages automatically via RAII.17. What happens if a destructor throws an exception?
std::terminate(), aborting the program immediately. As a rule, destructors should never let exceptions escape — catch and handle (or swallow, with logging) anything that might throw inside one.18. What is the difference between deep copy and shallow copy?
A shallow copy duplicates a class's member values as-is, including any pointer members — so both the original and the copy end up pointing at the same underlying resource. A deep copy allocates a new, independent resource and duplicates the actual data into it, so the two objects don't affect each other and don't double-free the same memory when destroyed.
19. What is `nullptr` and why is it preferred over `NULL` or `0`?
nullptr is a keyword with its own type, std::nullptr_t, that converts to any pointer type but not to an integer. NULL is typically just a macro for 0, which is ambiguous — it can be interpreted as either an integer or a pointer, causing overload resolution to sometimes pick the wrong function. nullptr removes that ambiguity entirely.20. Write a simple example demonstrating RAII.
raii-example.cpp
#include <iostream>
class FileGuard {
public:
explicit FileGuard(const char* path) {
file_ = std::fopen(path, "r");
std::cout << "File opened\n";
}
~FileGuard() {
if (file_) {
std::fclose(file_);
std::cout << "File closed automatically\n";
}
}
private:
std::FILE* file_;
};
void process() {
FileGuard guard("data.txt");
// Even if an exception is thrown here, guard's destructor
// still runs when the stack unwinds, closing the file.
}