C++

C++ Interview Questions and Answers: 30 Questions That Actually Get Asked

Most lists of C++ interview questions read like a glossary. Interviews don’t. A good interviewer asks one question, then follows up on your answer until they find the edge of what you know. This guide groups 30 questions by topic and, for each, tells you the answer and the follow-up that usually comes next.

Use it for freshers’ rounds, experienced-developer rounds, or a quick revision before an on-site.

Advertisements

Part 1: Language Basics

1. What is the difference between C and C++? C is procedural. C++ keeps everything C offers and adds classes, templates, references, function overloading, namespaces and language-level exception handling. Follow-up: “Is every valid C program valid C++?” No. For example, C++ requires explicit casts from void*, and new or class are reserved words.

2. What is the difference between a declaration and a definition? A declaration tells the compiler a name exists and what type it has. A definition creates the thing and reserves storage. extern int x; declares; int x = 5; defines. Follow-up: the One Definition Rule: a program may define each entity only once.

3. What is the difference between struct and class? Only the default access: members of a struct are public by default, members of a class are private. Inheritance defaults follow the same pattern.

4. What does static mean? It depends on where it appears. Inside a function it preserves a variable across calls. At namespace scope it limits a name to the current file. Inside a class it makes a member belong to the class rather than to each object.

5. What does const protect, and what is constexpr? const promises a value won’t be modified through that name. constexpr goes further and allows the value (or function result) to be computed at compile time, which matters for array sizes, templates and performance.

Advertisements

Part 2: Object-Oriented Programming

6. Name the four pillars of OOP. Encapsulation, abstraction, inheritance and polymorphism. Don’t just list them. Give one line each, for example: encapsulation is hiding data behind an interface so the internals can change safely.

7. Compile-time vs run-time polymorphism? Compile-time: function overloading and templates, resolved by the compiler. Run-time: virtual functions, resolved through the object’s actual type.

8. How do virtual functions work internally? Each class with virtual functions has a table of function pointers (the vtable). Each object carries a hidden pointer (the vptr) to its class’s table. A virtual call follows that pointer, so the correct override runs even through a base-class pointer.

9. Why should a base class have a virtual destructor? If you delete a derived object through a base pointer and the destructor isn’t virtual, only the base destructor runs. The derived part never gets cleaned up, which is undefined behaviour.

Advertisements
struct Base { virtual ~Base() = default; };
struct Derived : Base { ~Derived() { /* release resources */ } };
Base* p = new Derived;
delete p; // safe only because ~Base() is virtual
Advertisements

10. What is object slicing? Copying a derived object into a base-class value throws away the derived part. Pass polymorphic objects by pointer or reference to avoid it.

11. What is the diamond problem and how does C++ handle it? When a class inherits the same base through two paths, it gets two copies of that base. Virtual inheritance (class B : virtual public A) makes the paths share a single copy.

Advertisements

Part 3: Pointers, References and Memory

12. Pointer vs reference? A reference is an alias that must be bound at creation and can’t be reseated or null. A pointer can be null, can be reassigned, and supports arithmetic. Prefer references for required parameters and pointers when “no object” is a valid state.

13. What is the difference between new/delete and malloc/free? new allocates memory and runs the constructor; delete runs the destructor and frees memory. malloc/free only deal with raw bytes. Never mix the two families on one allocation, and use delete[] for memory from new[].

Advertisements

14. What is a memory leak, and what is a dangling pointer? A leak is memory you can no longer reach but never freed. A dangling pointer still points at memory that has already been freed or gone out of scope. Both are prevented far more reliably by RAII than by discipline.

15. What is RAII? Resource Acquisition Is Initialization: tie a resource’s lifetime to an object’s lifetime. The constructor acquires, the destructor releases, so cleanup happens even when an exception is thrown. Smart pointers, std::lock_guard and file streams all follow it.

16. Explain unique_ptr, shared_ptr and weak_ptr. unique_ptr has a single owner and can only be moved. shared_ptr uses reference counting for shared ownership. weak_ptr observes a shared_ptr without owning it, which is how you break reference cycles.

17. What is the Rule of Three / Five / Zero? If you need a custom destructor, copy constructor or copy assignment, you probably need all three (Rule of Three). C++11 adds move constructor and move assignment (Rule of Five). Best of all, design classes that own nothing directly so the compiler-generated versions are correct (Rule of Zero).

Advertisements

Part 4: Modern C++ (C++11 and Later)

18. What is move semantics? Instead of copying an object’s contents, a move transfers ownership of its internal resources and leaves the source in a valid but unspecified state. It makes returning big containers from functions cheap.

std::vector<int> make() {
std::vector<int> v(1'000'000, 7);
return v; // moved (or elided), not copied
}

19. lvalue vs rvalue? An lvalue has an identity you can take the address of. An rvalue is a temporary you can’t. An rvalue reference (T&&) binds to temporaries, which is what makes moving possible.

20. What does auto do, and when should you avoid it? It deduces the type from the initializer. It’s great for long iterator types, but avoid it when the deduced type hides intent or silently picks a proxy type.

21. What are lambdas and capture lists? A lambda is an unnamed function object. The capture list decides what it can see: [=] by value, [&] by reference, [x, &y] selectively. Capturing by reference something that outlives the scope is a classic bug.

22. What is nullptr and why replace NULL? NULL is just an integer in disguise and can pick the wrong overload. nullptr has its own type and converts only to pointer types.

Advertisements

Part 5: Templates and the STL

23. What are templates? Code written once for many types, generated by the compiler at compile time. They give you type safety with no run-time overhead, at the cost of longer compile times and harder error messages.

24. vector vs list vs deque? vector: contiguous, fastest iteration, amortised O(1) append. list: constant-time insertion at a known position, but poor cache behaviour. deque: fast at both ends, no single contiguous block. In practice, start with vector.

25. map vs unordered_map? map is a balanced tree: ordered keys, O(log n) operations. unordered_map is a hash table: no order, average O(1) operations, worst case O(n).

26. When do iterators get invalidated? Appending to a vector may reallocate and invalidate every iterator; erasing invalidates iterators at and after the erase point. Know the rules for the container you use.

Advertisements

Part 6: Questions That Show Up in Coding Rounds

27. Reverse a string in place.

void reverseStr(std::string& s) {
for (size_t i = 0, j = s.size(); i < j / 2; ++i)
std::swap(s[i], s[j - 1 - i]);
}
Advertisements

Mention that std::reverse(s.begin(), s.end()) exists, then explain why you wrote it by hand.

28. Implement a minimal unique_ptr-style class. Store a raw pointer, delete it in the destructor, delete the copy operations, implement the move operations. This single exercise covers RAII, the Rule of Five and move semantics.

29. What happens when you throw an exception from a destructor? If it happens during stack unwinding, std::terminate is called. Destructors are noexcept by default for this reason, so catch and handle errors inside them.

30. What is undefined behaviour, and why does it matter? Code the standard places no requirements on: out-of-bounds access, signed overflow, use after free, data races. It may crash, appear to work, or be “optimised” into something surprising. Interviewers love this question because it separates people who’ve debugged real systems from those who haven’t.

Advertisements

How to Prepare in One Week

  • Days 1–2: basics, OOP and the virtual-function mechanism. Write small programs, don’t just read.
  • Days 3–4: memory, smart pointers, move semantics. Re-implement a tiny vector and unique_ptr.
  • Days 5–6: STL containers and algorithms, then solve five or six array and string problems out loud.
  • Day 7: mock interview. Explain every answer in two sentences first, then go deeper only if asked.

Frequently Asked Questions

What are the most common C++ interview questions for freshers? Classes and objects, the four OOP pillars, constructors and destructors, pointers vs references, and function overloading.

What do experienced candidates get asked? vtables, move semantics, smart pointers, templates, multithreading basics, and how you would debug a crash or leak.

Is C++ still worth learning for interviews? Yes. It remains central to game engines, trading systems, embedded software, browsers and operating systems, where control over performance and memory matters.

Advertisements

Conclusion

Don’t memorise answers. Understand the why behind each one, because the follow-up question is where interviews are won. Pick the five topics you’re weakest on from this list, write a short program for each, and you’ll be better prepared than most candidates who only skim question banks.

Advertisements
Unknown's avatar

Shaky Byte

Your Saviour on your Coding Days

Leave a Reply