Quick answer: These 52 C++ interview questions and answers cover what is asked most in C++ developer, embedded software, game development and campus placement interviews: C++ basics, object-oriented programming, memory management, the STL, templates and modern C++, and common coding questions. Key answers include short code examples.
Read each answer, then close the page and explain it aloud in two or three sentences. That is exactly what interviewers check.
Contents
- C++ Basics
- Object-Oriented Programming
- Memory Management
- STL (Standard Template Library)
- Templates, Exceptions and Modern C++
- Coding Questions
- How to prepare
- FAQs
1. C++ Basics Interview Questions
Q1. What is C++?
C++ is a general-purpose, compiled programming language created by Bjarne Stroustrup as an extension of C. It supports procedural, object-oriented and generic programming, and is used for system software, game engines, embedded systems, trading systems and competitive programming.
Q2. What is the difference between C and C++?
C is procedural. C++ adds classes and objects, inheritance and polymorphism, function and operator overloading, references, templates, exception handling, namespaces and the Standard Template Library (STL).
Q3. What are the main features of C++?
Object-oriented programming, high performance close to hardware, manual memory control, templates for generic code, the STL, exception handling, and compatibility with most C code.
Q4. What is a namespace?
A namespace groups names to avoid conflicts between identifiers with the same name. The standard library lives in the std namespace, so we write std::cout or use 'using namespace std;' (better avoided in header files).
Q5. What is the difference between a reference and a pointer?
A reference is an alias for an existing variable: it must be initialised, cannot be null and cannot be re-bound. A pointer stores an address: it can be null, can be changed to point elsewhere and needs * to access the value.
int x = 10;
int& ref = x; // alias
int* ptr = &x; // address
ref = 20; // x becomes 20
*ptr = 30; // x becomes 30Q6. What is the difference between call by value, call by reference and call by pointer?
Call by value copies the argument, so changes do not affect the caller. Call by reference passes an alias, so changes affect the original. Call by pointer passes an address that the function dereferences.
Q7. What are inline functions?
The inline keyword suggests that the compiler replace a function call with the function body to avoid call overhead. It suits very small functions; the compiler may ignore the hint.
Q8. What is the difference between struct and class in C++?
They are almost the same. The only difference is the default access: members of a struct are public by default and members of a class are private by default.
Q9. What does const mean in different positions?
const int x means x cannot change. const int* p means the value pointed to cannot change through p. int* const p means the pointer itself cannot change. A const member function promises not to modify the object.
Q10. What is the auto keyword?
auto (C++11) lets the compiler deduce a variable's type from its initialiser, which makes code shorter, especially with iterators, as in auto it = v.begin().
2. Object-Oriented Programming Interview Questions
Q11. What are the four pillars of OOP in C++?
Encapsulation (bundling data and functions and controlling access), abstraction (exposing only essential features), inheritance (deriving classes from existing ones) and polymorphism (one interface with many behaviours).
Q12. What are constructors and destructors?
A constructor has the class name, no return type, and initialises an object when it is created. A destructor (~ClassName) runs automatically when the object goes out of scope or is deleted, and releases resources.
Q13. What are the types of constructors?
Default constructor (no arguments), parameterised constructor, copy constructor (creates an object from another object), and move constructor (C++11, takes resources from a temporary object).
Q14. What is the difference between a shallow copy and a deep copy?
The default copy constructor makes a shallow copy, copying pointer values, so two objects share the same memory and deleting one leaves the other with a dangling pointer. A deep copy allocates new memory and copies the data, which you implement in your own copy constructor.
Q15. What is the Rule of Three (and Five)?
If a class needs a custom destructor, copy constructor or copy assignment operator, it usually needs all three. Since C++11, the Rule of Five adds the move constructor and move assignment operator.
Q16. What is the this pointer?
this is a hidden pointer in every non-static member function that points to the object calling the function. It is used to distinguish members from parameters with the same name and to return the current object.
Q17. What are access specifiers?
public members are accessible everywhere, private members only inside the class (and friends), and protected members inside the class and its derived classes.
Q18. What is a friend function?
A friend function is not a member of a class but is allowed to access its private and protected members. It is declared inside the class with the friend keyword and is often used for operator overloading.
Q19. What are the types of inheritance in C++?
Single, multiple (one class inherits from several), multilevel, hierarchical and hybrid inheritance. C++ supports multiple inheritance of classes, unlike Java.
Q20. What is the diamond problem and how is it solved?
If classes B and C both inherit from A, and D inherits from both B and C, D gets two copies of A. Declaring the inheritance as virtual (class B : virtual public A) makes D share a single copy of A.
Q21. What is the difference between compile-time and runtime polymorphism?
Compile-time polymorphism uses function overloading, operator overloading and templates, resolved by the compiler. Runtime polymorphism uses virtual functions and is resolved while the program runs through a base class pointer or reference.
Q22. What is a virtual function?
A virtual function is declared in the base class with the virtual keyword so that a call through a base pointer or reference runs the derived class version.
class Shape { public: virtual double area() const { return 0; } virtual ~Shape() {} };
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() const override { return 3.14159 * r * r; }
};
Shape* s = new Circle(2);
std::cout << s->area(); // Circle::area runs
delete s;Q23. How do virtual functions work internally?
Each class with virtual functions has a vtable, a table of function pointers. Each object stores a hidden vptr pointing to its class's vtable. A virtual call looks up the function in the vtable at runtime.
Q24. What is a pure virtual function and an abstract class?
A pure virtual function is declared with = 0 and has no implementation in the base class. A class with at least one pure virtual function is abstract: it cannot be instantiated and derived classes must override the function.
Q25. Why should a base class destructor be virtual?
If you delete a derived object through a base pointer and the base destructor is not virtual, only the base destructor runs, so the derived part is not cleaned up and resources leak.
Q26. What is operator overloading?
Operator overloading gives operators such as +, == or << a meaning for user-defined types.
struct Point {
int x, y;
Point operator+(const Point& o) const { return {x + o.x, y + o.y}; }
};
Point c = Point{1, 2} + Point{3, 4}; // {4, 6}3. Memory Management Interview Questions
Q27. What is the difference between stack and heap memory?
The stack stores local variables and function calls; it is fast and freed automatically when a function returns. The heap stores memory allocated with new; it is larger but must be freed with delete (or managed by smart pointers).
Q28. What is the difference between new/delete and malloc/free?
new and delete are C++ operators that call constructors and destructors and return a typed pointer. malloc and free are C functions that only allocate and free raw memory. Never mix them, and use delete[] for arrays allocated with new[].
Q29. What is a memory leak?
A memory leak happens when heap memory is allocated but never freed, so the program's memory use keeps growing. Using RAII and smart pointers prevents most leaks.
Q30. What is a dangling pointer?
A dangling pointer points to memory that has already been freed or to a local variable that has gone out of scope. Using it causes undefined behaviour. Set pointers to nullptr after deleting, or use smart pointers.
Q31. What is RAII?
Resource Acquisition Is Initialisation means a resource, such as memory, a file or a lock, is acquired in a constructor and released in the destructor. Because destructors run automatically, resources are freed even when exceptions occur.
Q32. What are smart pointers?
Smart pointers manage heap memory automatically. unique_ptr has a single owner and cannot be copied. shared_ptr allows shared ownership with a reference count. weak_ptr observes a shared_ptr without owning it and breaks reference cycles.
#include <memory>
auto p = std::make_unique<int>(42);
auto s1 = std::make_shared<std::string>("hello");
auto s2 = s1; // reference count = 2
// memory freed automaticallyQ33. What are lvalues, rvalues and move semantics?
An lvalue has a name and an address, such as a variable. An rvalue is a temporary, such as the result of a + b. Move semantics (C++11) use rvalue references (&&) and std::move to transfer resources from temporaries instead of copying them, which is much faster for large objects.
4. STL (Standard Template Library) Interview Questions
Q34. What are the components of the STL?
Containers (vector, list, deque, set, map, unordered_map, stack, queue, priority_queue), iterators that traverse containers, and algorithms such as sort, find, binary_search and accumulate.
Q35. What is the difference between vector and array?
A built-in array has a fixed size known at compile time. A std::vector is a dynamic array that grows automatically, knows its own size, and works with STL algorithms. std::array is a fixed-size array with STL features.
Q36. How does a vector grow?
When a vector runs out of capacity, it allocates a bigger block (usually about double), moves the elements, and frees the old block. push_back is O(1) on average. Call reserve() when the size is known to avoid repeated reallocations.
Q37. What is the difference between map and unordered_map?
std::map is a sorted balanced binary search tree (usually red-black) with O(log n) operations. std::unordered_map is a hash table with O(1) average operations but no ordering.
Q38. What is the difference between set and multiset?
A set stores unique sorted elements. A multiset stores sorted elements and allows duplicates.
Q39. How do you use a priority_queue as a min-heap?
By default priority_queue is a max-heap. Pass greater<> as the comparator for a min-heap.
#include <queue>
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
pq.push(5); pq.push(1); pq.push(3);
std::cout << pq.top(); // 1Q40. What is iterator invalidation?
Some operations make existing iterators unusable. For example, inserting into a vector can reallocate memory and invalidate all its iterators, and erasing an element invalidates iterators at or after that position. Using an invalidated iterator is undefined behaviour.
Q41. How do you sort a vector in descending order and with a custom rule?
Use std::sort with a comparator, such as greater<int>() or a lambda.
std::sort(v.begin(), v.end(), std::greater<int>());
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) { return a.marks > b.marks; });5. Templates, Exceptions and Modern C++ Interview Questions
Q42. What are templates?
Templates let you write generic functions and classes that work with any data type. The compiler generates a version for each type used.
template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }
maxOf(3, 7); // int
maxOf(2.5, 1.5); // doubleQ43. How does exception handling work in C++?
Code that may fail goes in a try block. When an error occurs, throw an exception object; the matching catch block handles it. Catch by const reference, and prefer standard exceptions such as std::runtime_error.
Q44. What does noexcept mean?
noexcept tells the compiler and callers that a function will not throw exceptions. It enables optimisations, especially for move constructors used by containers such as vector.
Q45. What are lambda expressions?
A lambda is an anonymous function written inline, with a capture list for outside variables: [capture](parameters) { body }. They are widely used with STL algorithms.
int limit = 50;
auto passed = std::count_if(marks.begin(), marks.end(),
[limit](int m) { return m >= limit; });Q46. What are the key features of C++11 and later?
auto, range-based for loops, lambdas, smart pointers, move semantics, nullptr, constexpr, std::thread, unordered containers (C++11); generic lambdas (C++14); structured bindings and std::optional (C++17); concepts, ranges and modules (C++20).
Q47. What is the difference between NULL and nullptr?
NULL is usually defined as 0, an integer, which can cause wrong overload choices. nullptr (C++11) has its own pointer type, so it is the safe way to represent a null pointer.
Q48. What is constexpr?
constexpr marks variables and functions that can be evaluated at compile time, so results are computed by the compiler instead of at runtime.
6. Coding Questions Interview Questions
Q49. How do you reverse a string in C++?
Use std::reverse, or swap characters from both ends.
std::string s = "hello";
std::reverse(s.begin(), s.end()); // "olleh"Q50. How do you check whether a number is prime?
Test divisors only up to the square root of n.
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; 1LL * i * i <= n; ++i)
if (n % i == 0) return false;
return true;
}Q51. How do you count character frequency in a string?
Use an unordered_map or a 256-sized array.
std::unordered_map<char, int> freq;
for (char c : std::string("banana")) freq[c]++;Q52. How do you find duplicates in an array?
Insert elements into an unordered_set and report any element already present.
std::unordered_set<int> seen;
for (int x : arr)
if (!seen.insert(x).second) std::cout << x << ' ';How to Prepare for a C++ Interview
- Know OOP deeply: virtual functions, vtables, abstract classes and virtual destructors are favourite questions.
- Understand memory: stack versus heap, RAII, smart pointers and move semantics.
- Use the STL fluently: know the complexity of every common container operation.
- Practise DSA in C++: most coding rounds accept C++ and it is fast.
- Write modern C++: auto, lambdas, range-based loops and smart pointers show you are current.
Next steps: practise problem solving with DSA interview questions, test yourself with the DSA MCQs, and compare with Java interview questions.
More interview preparation: see all interview questions, including Python, SQL, SQL query, Java, JavaScript, React, C++, .NET, Spring Boot, Node.js, DSA, OOPs, DBMS, operating system, networking, machine learning, data science, AI, Excel, Power BI, DevOps, manual testing, Selenium, cyber security and HR.
Frequently Asked Questions
Which C++ topics are most important for interviews?
OOP and virtual functions, constructors and destructors, pointers versus references, memory management and smart pointers, the STL containers and their complexity, and templates appear in most C++ interviews.
Is C++ good for placements?
Yes. C++ is the most popular language for competitive programming and DSA rounds, and it is required for roles in systems, embedded software, game development and high-frequency trading.
Which C++ version should I learn?
Learn modern C++ (C++17 or C++20). Most interviewers expect you to know smart pointers, auto, lambdas and move semantics.
How should I prepare for a C++ interview?
Revise the concepts on this page, solve DSA problems in C++ using the STL, and practise explaining memory behaviour such as what happens when an object is copied, moved or destroyed.