C++ interview questions remain a fixture of technical hiring in India, from campus placement rounds at product companies to lateral interviews for backend, systems, and game-development roles. If you are preparing for a coding interview in 2026, a strong command of C++ fundamentals, object-oriented programming, memory management, and the Standard Template Library will decide how far you go. This guide collects 45+ frequently asked C++ interview questions with concise, correct answers and runnable code examples, organised by topic so you can revise fast and answer with confidence.
Whether you are a fresher in a TCS, Infosys, or Wipro placement drive, or an experienced engineer targeting Amazon, Google, or a fast-growing startup, the questions below cover both the breadth interviewers expect and the depth that separates strong candidates from the rest.
C++ Basics
1. What is C++?
C++ is a general-purpose programming language that supports both procedural and object-oriented programming. Created by Bjarne Stroustrup as an extension of C, it adds classes, inheritance, polymorphism, function and operator overloading, exception handling, and templates. It is statically typed, compiled, and gives the programmer direct control over memory, which is why it dominates systems programming, game engines, high-frequency trading, and performance-critical backends.
2. What is the difference between C and C++?
C is a procedural language, while C++ supports both procedural and object-oriented paradigms. The table below summarises the key differences that interviewers look for.
| Feature | C | C++ |
|---|---|---|
| Paradigm | Procedural | Procedural + Object-oriented |
| Data security | No data hiding | Encapsulation via access specifiers |
| Overloading | Not supported | Function and operator overloading |
| Memory allocation | malloc / free | new / delete (also malloc/free) |
| Namespaces | Not available | Available |
| Reference variables | Not available | Available |
| Standard library | C standard library | STL (containers, algorithms, iterators) |
3. What are the different data types in C++?
C++ data types fall into four groups: primitive (int, char, float, double, bool, void), derived (array, pointer, reference, function), enumeration (enum), and user-defined (class, struct, union, typedef). The size of each primitive type is implementation-defined, so use sizeof when you need exact widths.
4. What is a namespace and why is std used?
A namespace is a declarative region that groups identifiers to prevent naming collisions. The std namespace holds the entire C++ Standard Library, so std::cout and std::vector are qualified with the std:: prefix. Writing using namespace std; brings all names into scope, which is convenient for small programs but discouraged in headers because it pollutes the global namespace.
5. What is the difference between a struct and a class?
The only technical difference is the default access level: members of a struct are public by default, whereas members of a class are private by default. Default inheritance is also public for structs and private for classes. By convention, structs are used for passive data aggregates and classes for types with behaviour and invariants.
6. What does the auto keyword do?
auto lets the compiler deduce a variable's type from its initialiser at compile time. It reduces verbosity, especially with iterators and templates. For example, auto it = v.begin(); avoids spelling out std::vector<int>::iterator. Note that auto strips references and const-ness unless you write auto& or const auto&.
7. What is the mutable keyword?
mutable allows a non-static data member to be modified even inside a const member function or when the object itself is const. It is typically used for caching, reference counts, or mutex members that do not affect the logical state of the object.
Object-Oriented Programming (OOP)
8. What are the four pillars of OOP?
The four pillars are encapsulation, abstraction, inheritance, and polymorphism. Encapsulation bundles data with the functions that operate on it; abstraction exposes only essential behaviour and hides implementation; inheritance lets one class reuse and extend another; polymorphism lets a single interface work with different underlying types.
9. What is encapsulation?
Encapsulation is the bundling of data and methods into a single unit (a class), with controlled access through access specifiers. Data members are kept private and exposed through public getter and setter methods, protecting invariants and hiding internal representation.
class BankAccount {
private:
double balance; // hidden state
public:
void deposit(double amount) { // controlled access
if (amount > 0) balance += amount;
}
double getBalance() const { return balance; }
};
10. What is abstraction, and how is it different from encapsulation?
Abstraction means showing only the essential features of an object while hiding the irrelevant implementation details, achieved through abstract classes and interfaces. Encapsulation is about protecting data by wrapping it inside a class. In short, abstraction solves a problem at the design level, encapsulation solves it at the implementation level.
11. What is inheritance and what types does C++ support?
Inheritance lets a derived class acquire the members of a base class, modelling an "is-a" relationship and enabling code reuse. C++ supports five types: single, multiple, multilevel, hierarchical, and hybrid inheritance. Multiple inheritance (a class deriving from more than one base) is unique to C++ among mainstream OOP languages and introduces the diamond problem, discussed below.
12. What is polymorphism and what are its types?
Polymorphism means "many forms," letting the same interface behave differently for different types. C++ has two kinds:
- Compile-time (static) polymorphism through function overloading and operator overloading, resolved by the compiler (early binding).
- Runtime (dynamic) polymorphism through virtual functions, resolved during execution based on the actual object type (late binding).
13. What is the difference between function overloading and function overriding?
This comparison is a favourite in placement interviews.
| Aspect | Overloading | Overriding |
|---|---|---|
| Signature | Same name, different parameters | Same name and same signature |
| Inheritance | Not required | Requires base and derived classes |
| Binding | Compile-time | Runtime (needs virtual) |
| Polymorphism | Static | Dynamic |
14. What is an abstract class?
An abstract class is a class that contains at least one pure virtual function and therefore cannot be instantiated. It serves as an interface that derived classes must implement. Attempting to create an object of an abstract class is a compile-time error.
class Shape {
public:
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default;
};
15. What are access specifiers in C++?
There are three: public members are accessible from anywhere, protected members are accessible within the class and its derived classes, and private members are accessible only within the same class. They are the mechanism that enforces encapsulation.
16. What are friend functions and friend classes?
A friend function or friend class is granted access to the private and protected members of another class, even though it is not a member of that class. Friendship deliberately breaks encapsulation for specific, trusted cases such as operator overloading that needs symmetric access to two objects. Friendship is not inherited and not mutual unless declared both ways.
Pointers and References
17. What is the difference between a pointer and a reference?
A pointer stores a memory address and can be reassigned or set to null, while a reference is an alias for an existing variable and must be initialised at declaration.
| Aspect | Pointer | Reference |
|---|---|---|
| Reassignment | Can point elsewhere | Bound permanently |
| Null | Can be nullptr | Cannot be null |
| Initialisation | Optional | Mandatory |
| Arithmetic | Supported | Not applicable |
| Syntax | Dereference with * | Used like the variable |
18. What is a void pointer?
A void pointer (void*) is a generic pointer that can hold the address of any data type. Because it has no associated type, it cannot be dereferenced directly and must be cast to a concrete pointer type first. It is common in C-style APIs like malloc, which returns void*.
19. What is the this pointer?
this is an implicit pointer available inside every non-static member function that points to the object on which the function was invoked. It is used to disambiguate members from parameters of the same name, and to return the current object by reference for method chaining.
20. What is the difference between call by value and call by reference?
In call by value, a copy of the argument is passed, so changes inside the function do not affect the original. In call by reference, the address (via pointer or reference) is passed, so the function operates on the original variable. Call by reference avoids copying large objects and is also achieved cheaply with const T& when you only need read access.
void byValue(int x) { x = 10; } // caller unchanged
void byRef(int& x) { x = 10; } // caller modified
Memory Management
21. What is the difference between new/delete and malloc/free?
new and delete are operators, while malloc and free are library functions. new calls the constructor and returns a correctly typed pointer, throwing std::bad_alloc on failure. malloc allocates raw memory, returns void*, does not call constructors, and returns nullptr on failure. In C++ you should prefer new/delete, or better, smart pointers.
22. What is the difference between delete and delete[]?
Use delete to free memory allocated for a single object and delete[] to free memory allocated for an array with new[]. Mismatching them (for example, delete on an array) is undefined behaviour and a common source of leaks and crashes.
23. What is RAII?
RAII (Resource Acquisition Is Initialization) ties a resource's lifetime to the lifetime of an object. The resource (memory, file handle, mutex lock) is acquired in the constructor and released in the destructor, so it is cleaned up automatically when the object goes out of scope, even if an exception is thrown. RAII is the foundation of exception-safe C++ and the reason C++ does not need a garbage collector or try-with-resources.
24. What are smart pointers?
Smart pointers are RAII wrappers in <memory> that manage dynamic memory automatically and prevent leaks.
unique_ptrmodels exclusive ownership; it cannot be copied, only moved.shared_ptrmodels shared ownership using reference counting; the object is destroyed when the last owner is gone.weak_ptris a non-owning observer of ashared_ptr, used to break circular references.
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(42);
std::shared_ptr<int> s = std::make_shared<int>(10);
25. What is the difference between shallow copy and deep copy?
A shallow copy copies member values as-is, so pointer members in both objects point to the same memory, and a change through one affects the other (and double-free on destruction). A deep copy allocates new memory and copies the pointed-to contents, giving each object an independent resource. Classes that own raw resources must implement a proper copy constructor and copy assignment operator to perform deep copies.
26. What are move semantics and rvalue references?
Move semantics, introduced in C++11, transfer resources from a temporary (rvalue) object instead of copying them, which is far cheaper for objects that own heap memory. An rvalue reference is written T&& and binds to temporaries. A move constructor and move assignment operator "steal" the internals of the source and leave it in a valid empty state, powering fast returns from functions and efficient container growth.
Constructors and Destructors
27. What is a constructor and what types exist?
A constructor is a special member function with the same name as the class and no return type, invoked automatically when an object is created. The main types are the default constructor (no parameters), the parameterised constructor, and the copy constructor. C++11 also adds the move constructor.
28. What is a copy constructor?
A copy constructor initialises a new object as a copy of an existing object of the same class, with the signature ClassName(const ClassName& other). It is called when an object is passed by value, returned by value, or explicitly copied. If you do not define one, the compiler generates a member-wise (shallow) copy.
29. What is a destructor, and can it be overloaded?
A destructor is a member function prefixed with a tilde (~ClassName), takes no parameters, returns nothing, and is called automatically when an object is destroyed to release resources. A class can have only one destructor; it cannot be overloaded.
30. In what order are constructors and destructors called in inheritance?
Constructors run base class first, then derived class. Destructors run in the exact reverse order: derived class first, then base class. This guarantees that a derived object is fully built on top of a constructed base, and torn down before the base is destroyed.
31. What is a virtual destructor and why is it needed?
A virtual destructor ensures that when you delete a derived object through a base class pointer, the derived destructor runs before the base destructor. Without it, only the base destructor is called, leaking the derived part's resources. Rule of thumb: any class with virtual functions that is meant to be inherited from should have a virtual destructor.
class Base {
public:
virtual ~Base() { } // ensures correct cleanup
};
Virtual Functions and Vtables
32. What is a virtual function?
A virtual function is a member function declared with the virtual keyword in a base class and overridden in derived classes. It enables runtime polymorphism: when called through a base pointer or reference, the version corresponding to the actual object type is executed via dynamic dispatch.
33. What is the difference between a virtual function and a pure virtual function?
A virtual function has a body and provides a default implementation that derived classes may override. A pure virtual function is declared with = 0, has no implementation (usually), and forces derived classes to override it. A class with any pure virtual function becomes abstract.
34. What is a vtable and a vptr?
A vtable (virtual table) is a per-class array of function pointers to the class's virtual functions. Each object of a polymorphic class holds a hidden pointer, the vptr, to its class's vtable. When a virtual function is called through a base pointer, the runtime follows the vptr to the correct vtable entry and dispatches to the right override. This indirection is how C++ implements dynamic dispatch.
35. Can a constructor be virtual? What happens when you call a virtual function inside a constructor?
A constructor cannot be virtual because the vtable is not fully set up until the object is constructed. If you call a virtual function inside a constructor, it dispatches to the current class's version, not a derived override, because the derived part does not yet exist. The same applies inside destructors.
STL (Standard Template Library)
36. What is the STL?
The Standard Template Library is a collection of generic, template-based classes and functions providing common data structures and algorithms. Its three core components are containers (data structures), algorithms (sort, find, accumulate), and iterators (the glue that lets algorithms work on containers).
37. What is the difference between vector, list, and deque?
| Container | Storage | Random access | Insert in middle |
|---|---|---|---|
| vector | Contiguous array | O(1) | O(n) |
| list | Doubly linked list | Not supported | O(1) |
| deque | Segmented blocks | O(1) | O(n) |
A vector is the default choice; use list when you insert and delete frequently in the middle, and deque when you need fast insertion at both ends.
38. What is the difference between map and unordered_map?
A map stores keys in sorted order using a self-balancing red-black tree, giving O(log n) lookup, insertion, and deletion. An unordered_map uses a hash table, giving average O(1) operations but no ordering. Choose map when you need sorted iteration, and unordered_map when you need the fastest average lookups.
39. What are iterators and what categories exist?
An iterator is an object that points to an element in a container and lets you traverse it, behaving like a generalised pointer. There are five categories: input, output, forward, bidirectional, and random access. A vector provides random-access iterators, while a list provides bidirectional iterators.
#include <vector>
std::vector<int> v = {1, 2, 3};
for (auto it = v.begin(); it != v.end(); ++it)
std::cout << *it << " "; // prints 1 2 3
40. What happens if you insert duplicate keys into a set or map?
Both std::set and std::map store unique keys, so a duplicate insertion is ignored. The insert function returns a std::pair<iterator, bool> where the bool is false when the key already existed. Use multiset or multimap if you need to store duplicates.
Templates
41. What are templates in C++?
Templates enable generic programming by letting you write functions and classes that work with any type, with the concrete code generated by the compiler at instantiation. Function templates parameterise algorithms, and class templates (such as vector<T>) parameterise data structures. Templates are resolved entirely at compile time, so there is no runtime cost.
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
// maximum(3, 7) and maximum(2.5, 1.1) both work
42. What is the difference between a function template and a class template?
A function template generates a family of functions that differ only in the types they operate on, with the type usually deduced from the arguments. A class template generates a family of classes, and the type is normally supplied explicitly, as in std::vector<int>. Both are compiled into concrete code only for the types actually used.
Operator Overloading
43. What is operator overloading?
Operator overloading lets you redefine the meaning of operators like +, ==, or << for user-defined types, making objects behave intuitively. It is a form of compile-time polymorphism. Not all operators can be overloaded: the scope resolution ::, member access ., ternary ?:, and sizeof cannot be.
class Complex {
double re, im;
public:
Complex(double r, double i) : re(r), im(i) {}
Complex operator+(const Complex& o) const {
return Complex(re + o.re, im + o.im);
}
};
44. What is the difference between prefix and postfix increment overloading?
The prefix operator++() takes no parameter, increments the object, and returns a reference to it. The postfix operator++(int) takes a dummy int parameter to distinguish it, returns a copy of the old value, then increments. Prefix is generally more efficient because it avoids creating a temporary copy.
45. What is the scope resolution operator?
The scope resolution operator :: accesses a name that belongs to a particular scope: a class member defined outside the class (ClassName::method), a namespaced name (std::cout), a static member, or a global variable hidden by a local one. It also resolves ambiguity in multiple inheritance.
Coding and Output Questions
46. What will this program output?
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base ctor "; }
~Base() { cout << "Base dtor "; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived ctor "; }
~Derived() { cout << "Derived dtor "; }
};
int main() {
Derived d;
}
Output: Base ctor Derived ctor Derived dtor Base dtor. Constructors run base-to-derived, destructors run derived-to-base, confirming question 30.
47. Explain the output of pointer arithmetic here.
int arr[] = {10, 20, 30, 40};
int* p = arr;
cout << *(p + 2) << " " << *p + 2;
Output: 30 12. *(p + 2) dereferences the third element (30), while *p + 2 dereferences the first element (10) and adds 2, giving 12. Operator precedence makes the difference, which is exactly what the interviewer is testing.
48. What is the diamond problem and how is it solved?
The diamond problem arises in multiple inheritance when two base classes both derive from a common ancestor, so the most-derived class ends up with two copies of that ancestor. It is solved with virtual inheritance, declaring the shared base as virtual, which ensures a single shared instance.
class A { public: int x; };
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {}; // single A, no ambiguity
49. What is the output of shallow copy misuse?
If a class holds a raw pointer and relies on the compiler-generated copy constructor, copying an object shares the same allocation. When both objects are destroyed, the destructor runs delete twice on the same address, causing a double-free crash. The fix is a user-defined deep-copy constructor and assignment operator, or a smart pointer, tying back to question 25.
How to Prepare for a C++ Interview
A practical plan for the weeks before your interview or placement drive:
- Master the fundamentals first. Pointers, references, memory management, and the OOP pillars appear in nearly every interview. Be able to explain, not just recognise, each concept.
- Write code by hand and on a whiteboard. Many Indian campus rounds still ask you to code on paper or a shared editor without a compiler, so practise tracing output and spotting undefined behaviour manually.
- Learn the STL deeply. Know the time complexity of
vector,map,unordered_map, andsetoperations cold, and be comfortable with iterators and common algorithms. - Practise output and debugging questions. Constructor and destructor ordering, virtual dispatch, operator precedence, and shallow-copy bugs are classic traps.
- Do timed mock interviews. Reading answers is not the same as saying them under pressure. Rehearsing with realistic questions and feedback is the single most effective way to fix hesitation and filler. A structured AI mock interview from Goodspace lets you practise C++ and CS-fundamentals rounds on demand and get instant, specific feedback on your answers.
- Revise projects and DSA together. Experienced candidates should be ready to discuss how they used C++ features in real projects, from RAII wrappers to move semantics for performance.
Do a final full-length rehearsal a day or two before the real thing so the format feels familiar. You can run an end-to-end mock interview on Goodspace to simulate the pressure of a live panel and walk in calm.
Frequently Asked Questions
1. Are C++ interview questions still relevant in 2026? Yes. C++ powers operating systems, browsers, databases, game engines, and low-latency trading systems, and demand for skilled C++ engineers in India remains strong across product companies and startups.
2. What C++ topics are most important for freshers? Focus on the basics, the four OOP pillars, pointers and references, constructors and destructors, virtual functions, and core STL containers. These cover the vast majority of campus placement questions.
3. Which C++ version should I study for interviews?
Learn modern C++ (C++11 and later), especially smart pointers, move semantics, auto, lambda expressions, and range-based for loops, since interviewers increasingly expect familiarity with these.
4. How many questions are enough to feel prepared? Depth beats count. Master the 45+ questions in this guide well enough to explain and code each one, then extend into data structures and algorithms, which are tested alongside C++ in most interviews.
5. What is the difference between an easy and a hard C++ question? Easy questions test definitions (what is encapsulation), while hard ones test consequences and edge cases (why you need a virtual destructor, what a shallow copy does on destruction, how the vtable dispatches a call). Prepare for both.
6. How do I get better at answering under pressure? Simulate the real setting with timed mock interviews and review your recordings or feedback. Practising the spoken delivery, not just the written answer, is what turns knowledge into a confident performance on interview day.
Conclusion
C++ interviews reward candidates who understand the language deeply rather than those who have merely memorised definitions. Command the fundamentals, know why virtual destructors and RAII matter, be fluent with the STL, and practise tracing tricky output questions. Combine that with focused, timed mock interview practice and you will walk into your next placement round ready to perform.






