Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Interview questions › C++

C++ interview questions

1. What is C++?

Easy

A compiled, statically typed language that extends C with object-oriented programming, templates and the STL. It gives low-level control over memory with high performance — used for games, browsers, databases and competitive programming.

2. C vs C++?

Easy

C is procedural. C++ adds classes and objects, inheritance and polymorphism, function and operator overloading, references, templates, exceptions, namespaces and the STL. C++ is (almost) a superset of C.

3. What are the four pillars of OOP in C++?

Easy

Encapsulation (private data, public methods), Abstraction (hide details behind interfaces), Inheritance (class Dog : public Animal), Polymorphism (function overloading at compile time, virtual functions at runtime).

4. struct vs class in C++?

Easy

They are the same except for the default access: members and inheritance are public by default in a struct and private in a class. By convention, struct is used for plain data.

5. What are access specifiers?

Easy

public — accessible everywhere. private — only inside the class (and friends). protected — inside the class and its derived classes.

6. What is a constructor? Types of constructors?

Easy

A special function called when an object is created, with the class name and no return type. Types: default, parameterized, copy (A(const A&)), move (A(A&&)). A constructor can use an initializer list: A(int x) : x(x) {}.

7. What is a destructor?

Easy

~ClassName() runs automatically when an object goes out of scope or is deleted, to release resources (memory, files, locks). A class can have only one destructor, with no arguments.

8. What is a copy constructor? When is it called?

Medium

A(const A& other) creates a new object as a copy of an existing one. It runs when passing or returning by value, or initialising one object from another (A b = a;). The default one copies member by member (shallow).

9. Shallow copy vs deep copy?

Medium

A shallow copy copies pointer values, so both objects point to the same memory — deleting one breaks the other. A deep copy allocates new memory and copies the data. Classes that own raw memory need a custom copy constructor and assignment operator.

10. What is the rule of three / five / zero?

Hard

Three: if a class needs a custom destructor, copy constructor or copy assignment, it probably needs all three. Five adds move constructor and move assignment. Zero: prefer members that manage themselves (vector, string, smart pointers) so you need none of them.

11. What is a reference? Reference vs pointer?

Medium

A reference is an alias for an existing variable (int& r = x;). It must be initialised, cannot be null and cannot be re-bound. A pointer stores an address, can be null, can be changed to point elsewhere and supports arithmetic.

12. What is the `this` pointer?

Easy

A hidden pointer inside non-static member functions that points to the object the function was called on. Used to tell members from parameters (this->x = x) and to return the object (return *this).

13. Function overloading vs overriding?

Easy

Overloading: same name, different parameters, in the same scope — chosen at compile time. Overriding: a derived class redefines a virtual function of its base with the same signature — chosen at runtime.

14. What are virtual functions?

Medium

Functions declared virtual in a base class so the call is decided by the actual object type at runtime, even through a base pointer or reference.

struct Shape { virtual double area() const { return 0; } };
struct Circle : Shape { double r; double area() const override { return 3.14 * r * r; } };

15. How do virtual functions work internally (vtable)?

Hard

Each class with virtual functions has a vtable — a table of function pointers. Each object stores a hidden vptr to its class's vtable. A virtual call follows the vptr and calls the right entry, which is why it costs one extra lookup.

16. What is a pure virtual function and an abstract class?

Medium

A pure virtual function has no body in the base class: virtual void draw() = 0;. A class with at least one is abstract and cannot be instantiated — it works like an interface that derived classes must implement.

17. Why should a base class have a virtual destructor?

Hard

If you delete a derived object through a base pointer and the destructor is not virtual, only the base destructor runs — the derived part leaks. Make the base destructor virtual whenever the class is meant to be inherited from.

18. What is multiple inheritance and the diamond problem?

Hard

A class can inherit from several bases. In a diamond (B and C both inherit A, D inherits B and C), D gets two copies of A. Virtual inheritance (class B : virtual public A) keeps a single shared copy.

19. What is operator overloading?

Medium

Giving operators a meaning for your own types.

struct Point {
    int x, y;
    Point operator+(const Point& o) const { return {x + o.x, y + o.y}; }
};

Operators like ::, . and ?: cannot be overloaded.

20. What is a friend function?

Medium

A non-member function (or class) declared with friend inside a class that can access its private and protected members — often used for operator<< so objects can be printed with cout.

21. What are static members?

Easy

A static data member is shared by all objects of the class (one copy). A static member function belongs to the class, has no this, and can only access static members. Called as ClassName::fn().

22. What are inline functions?

Medium

A hint (inline) that the compiler may replace a call with the function body to avoid call overhead for tiny functions. Modern compilers decide inlining themselves; inline mainly allows a function to be defined in a header used by many files.

23. new/delete vs malloc/free?

Medium

new allocates memory and calls the constructor, returns the right type and throws bad_alloc on failure; delete calls the destructor. malloc/free only handle raw bytes. Use new[] with delete[] for arrays — never mix them up.

24. What is a memory leak? How do you avoid it?

Medium

Memory allocated with new that is never deleted, so it can't be reused. Avoid it with RAII: let objects own resources — use std::vector, std::string and smart pointers instead of raw new/delete.

25. What is RAII?

Hard

"Resource Acquisition Is Initialization": a resource is acquired in a constructor and released in the destructor, so it is freed automatically when the object goes out of scope — even when an exception is thrown. lock_guard, vector and smart pointers all use RAII.

26. What are smart pointers?

Hard

unique_ptr — single owner, cannot be copied, only moved. shared_ptr — shared ownership with a reference count; frees when the last owner goes. weak_ptr — non-owning observer of a shared_ptr, used to break reference cycles. Create them with make_unique / make_shared.

27. What is the STL?

Easy

The Standard Template Library: containers (vector, list, deque, set, map, unordered_map, stack, queue, priority_queue), iterators, and algorithms (sort, find, binary_search, lower_bound, reverse, accumulate).

28. vector vs array vs list?

Easy

A built-in array has a fixed size. std::vector is a dynamic array — contiguous, O(1) random access, amortised O(1) push_back. std::list is a doubly linked list — O(1) insert/erase anywhere with an iterator, but no random access and poor cache use.

29. map vs unordered_map?

Easy

map is a balanced BST (red-black tree): keys stay sorted, operations are O(log n). unordered_map is a hash table: no order, average O(1), worst case O(n). Use map when you need ordered keys or lower_bound.

30. set vs multiset vs unordered_set?

Easy

set keeps unique sorted keys (O(log n)). multiset allows duplicates, still sorted. unordered_set keeps unique keys in a hash table — no order, average O(1).

31. How does vector grow? What is its capacity?

Medium

size() is the number of elements; capacity() is how many fit before reallocating. When full, push_back allocates a bigger block (usually 1.5× or 2×), moves the elements and frees the old block — so iterators can become invalid. Call reserve(n) if you know the size.

32. What is a priority_queue? How do you make a min-heap?

Medium

A heap container where top() is the largest element by default. For a min-heap: priority_queue<int, vector<int>, greater<int>> pq;. push and pop are O(log n), top is O(1).

33. lower_bound vs upper_bound?

Medium

On a sorted range, lower_bound(x) returns the first position with value ≥ x, upper_bound(x) the first position with value > x. Their difference is the count of x. Both are O(log n).

34. How do you sort with a custom comparator?

Medium

sort(v.begin(), v.end(), [](const auto& a, const auto& b) {
    if (a.marks != b.marks) return a.marks > b.marks;   // marks descending
    return a.name < b.name;                            // then name ascending
});

The comparator must be a strict weak ordering — never return true for equal elements.

35. What are templates?

Medium

Code written for any type, with the type filled in at compile time.

template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }

The STL is built on templates. Class templates work the same way (template <typename T> class Stack).

36. What is the difference between `const` before and after `*`?

Hard

const int* p — pointer to a const int (the value can't change through p). int* const p — const pointer (it can't point elsewhere). const int* const p — both. A const member function (int get() const) promises not to modify the object.

37. Pass by value vs reference vs pointer?

Easy

By value copies the argument. By reference (int&) works on the original with no copy. By pointer (int*) also works on the original but can be null. Pass large objects as const T& to avoid copies.

38. What is move semantics?

Hard

Instead of copying a temporary object's data, a move constructor (A(A&&)) steals its resources (e.g. the internal buffer pointer) and leaves it empty. std::move turns a named object into an rvalue to allow moving. It makes returning and passing big objects cheap.

39. lvalue vs rvalue?

Hard

An lvalue has a name and an address (x, arr[2]). An rvalue is a temporary without a lasting address (5, a + b, a function returning by value). T& binds to lvalues, T&& to rvalues.

40. What are exceptions in C++?

Medium

throw raises an error, try / catch handles it. Catch by const reference: catch (const std::exception& e) { cerr << e.what(); }. During unwinding, destructors of local objects run — which is why RAII keeps resources safe.

41. What are namespaces?

Easy

Named scopes that prevent name clashes between libraries: std::vector. Avoid using namespace std; in headers, since it leaks every std name into files that include them.

42. What is `auto` and range-based for?

Easy

auto lets the compiler deduce a variable's type: auto it = m.find(k);. A range-based for loops over a container: for (const auto& x : v). Use auto& to modify the elements and const auto& to avoid copies.

43. What are lambdas?

Medium

Anonymous functions written inline: [capture](params) { body }. [=] captures by value, [&] by reference, [x, &y] specific variables.

int k = 3;
auto mul = [k](int x) { return x * k; };

44. What is a dangling pointer?

Medium

A pointer that points to memory that was freed or went out of scope (e.g. returning the address of a local variable). Using it is undefined behaviour. Set pointers to nullptr after delete, or better, use smart pointers.

45. What is undefined behaviour? Give examples.

Hard

Code whose result the standard doesn't define, so anything can happen: reading out of array bounds, using uninitialised variables, signed integer overflow, dereferencing null or dangling pointers, modifying a variable twice without sequencing.

46. What is the difference between `#define` and `const`?

Medium

#define is a preprocessor text replacement with no type and no scope — errors are hard to trace. const / constexpr variables are typed, scoped and checked by the compiler. Prefer constexpr for constants.

47. Why is `ios::sync_with_stdio(false)` used in competitive programming?

Easy

It unties C++ streams from C's stdio, and cin.tie(nullptr) stops cin from flushing cout before every read. Together they make cin/cout much faster for large input. After this, don't mix cin with scanf.

48. What is the size of an empty class?

Medium

At least 1 byte, so that every object has a unique address. (An empty base class inside a derived class can take 0 bytes thanks to the empty base optimisation.)

49. Write a function to reverse a string in C++.

Easy

string rev(string s) {
    int i = 0, j = (int)s.size() - 1;
    while (i < j) swap(s[i++], s[j--]);
    return s;
}
// or simply: reverse(s.begin(), s.end());

O(n) time, O(1) extra space for the in-place version.

50. What is the time complexity of common STL operations?

Medium

vector: index O(1), push_back amortised O(1), insert in the middle O(n). set/map: insert, find, erase O(log n). unordered_map: average O(1). sort: O(n log n). binary_search/lower_bound: O(log n). priority_queue: push/pop O(log n).

More topics