Top 50 C++ Interview Questions with Answers
Master the most frequently asked C++ interview questions and ace your next technical interview
Introduction
C++ remains one of the most popular programming languages for system programming, game development, and performance-critical applications. Whether you're preparing for a job interview at a tech giant or a startup, mastering C++ fundamentals is essential.
This comprehensive guide covers the 50 most frequently asked C++ interview questions, organized by topic for easy navigation. Each question includes a detailed answer with code examples where applicable.
Basic C++ Concepts (Q1-Q10)
Q1. What is the difference between C and C++?
Answer:
- Paradigm: C is procedural, C++ supports both procedural and OOP
- Classes and Objects: C++ has classes, C doesn't
- Function Overloading: Supported in C++, not in C
- Operator Overloading: Available in C++, not in C
- Namespace: C++ has namespace feature, C doesn't
- Exception Handling: C++ supports try-catch, C doesn't
- Input/Output: C uses printf/scanf, C++ uses cin/cout
- Memory Management: C++ has new/delete operators, C uses malloc/free
Q2. What is the difference between struct and class in C++?
Answer: The only difference is the default access specifier:
- struct: Members are
publicby default - class: Members are
privateby default
// Struct - public by default
struct Point {
int x, y; // public by default
};
// Class - private by default
class Point {
int x, y; // private by default
public:
Point(int a, int b) : x(a), y(b) {}
};
Q3. What is the difference between malloc() and new in C++?
Answer:
| malloc() | new |
|---|---|
| C library function | C++ operator |
| Returns void* (needs casting) | Returns typed pointer |
| Doesn't call constructor | Calls constructor |
| Size specified in bytes | Size calculated automatically |
| Can't be overloaded | Can be overloaded |
| Use free() to deallocate | Use delete to deallocate |
// malloc example
int *p = (int*)malloc(sizeof(int));
free(p);
// new example
int *p = new int;
delete p;
Q4. What is the difference between reference and pointer?
Answer:
- Initialization: Reference must be initialized, pointer can be NULL
- Reassignment: Reference cannot be reassigned, pointer can
- Memory: Reference is an alias (no separate memory), pointer has its own memory
- Arithmetic: Pointer arithmetic allowed, reference arithmetic not allowed
- Indirection: Reference doesn't need dereferencing, pointer needs *
int x = 10;
int &ref = x; // Reference - must be initialized
int *ptr = &x; // Pointer - can be NULL
ref = 20; // Direct assignment
*ptr = 20; // Needs dereferencing
int y = 30;
// ref = y; // This changes x, not ref itself
ptr = &y; // Pointer can be reassigned
Q5. What is the difference between pass by value, pass by reference, and pass by pointer?
Answer:
// Pass by value - creates copy
void func1(int x) {
x = 100; // Original variable not affected
}
// Pass by reference - alias to original
void func2(int &x) {
x = 100; // Original variable modified
}
// Pass by pointer - address passed
void func3(int *x) {
*x = 100; // Original variable modified
}
int main() {
int a = 10;
func1(a); // a is still 10
func2(a); // a becomes 100
a = 10;
func3(&a); // a becomes 100
return 0;
}
Q6. What is the difference between compile-time and runtime polymorphism?
Answer:
- Compile-time (Static) Polymorphism:
- Achieved through function overloading and operator overloading
- Resolved at compile time
- Faster execution
- Runtime (Dynamic) Polymorphism:
- Achieved through virtual functions and function overriding
- Resolved at runtime using virtual table
- More flexible but slightly slower
Q7. What is a namespace in C++?
Answer: A namespace is a declarative region that provides a scope to identifiers (names of types, functions, variables, etc.) inside it. It helps avoid naming conflicts.
namespace Math {
int add(int a, int b) {
return a + b;
}
}
namespace Physics {
int add(int a, int b) { // No conflict!
return a * b;
}
}
int main() {
int result1 = Math::add(5, 3); // 8
int result2 = Physics::add(5, 3); // 15
return 0;
}
Q8. What is the difference between #include <file> and #include "file"?
Answer:
- #include <file>: Searches in system directories first (standard library headers)
- #include "file": Searches in current directory first, then system directories (user-defined headers)
Q9. What is the difference between iostream.h and iostream?
Answer:
- iostream.h: Old C++ style (deprecated), doesn't use namespace std
- iostream: Modern C++ style, uses namespace std
Q10. What is the use of const keyword in C++?
Answer: const keyword has multiple uses:
- const variable: Value cannot be modified
- const pointer: Pointer cannot point to different address
- Pointer to const: Value pointed to cannot be modified
- const member function: Cannot modify member variables
- const parameter: Parameter cannot be modified in function
const int x = 10; // x cannot be modified
int *const ptr = &x; // ptr cannot point elsewhere
const int *ptr2 = &x; // *ptr2 cannot be modified
class MyClass {
int value;
public:
void func() const { // Cannot modify 'value'
// value = 10; // Error!
}
};
Object-Oriented Programming (Q11-Q20)
Q11. What are the four pillars of OOP?
Answer:
- Encapsulation: Binding data and methods together, data hiding
- Inheritance: Deriving new classes from existing ones
- Polymorphism: Same interface, different implementations
- Abstraction: Hiding implementation details, showing only essential features
Q12. What is the difference between abstraction and encapsulation?
Answer:
- Abstraction: Hiding implementation details, showing what an object does (interface)
- Encapsulation: Wrapping data and methods together, controlling access (data hiding)
Abstraction is about "what", Encapsulation is about "how".
Q13. What is a virtual function? Why do we need it?
Answer: A virtual function is a member function declared with the virtual keyword. It enables runtime polymorphism.
class Base {
public:
virtual void show() { // Virtual function
cout << "Base class" << endl;
}
};
class Derived : public Base {
public:
void show() { // Overrides base class function
cout << "Derived class" << endl;
}
};
int main() {
Base *ptr = new Derived();
ptr->show(); // Calls Derived::show() due to virtual
return 0;
}
Why needed: Without virtual, the base class function would be called (early binding). With virtual, the derived class function is called (late binding).
Q14. What is a pure virtual function and abstract class?
Answer:
- Pure Virtual Function: Virtual function with no implementation (initialized to 0)
- Abstract Class: Class with at least one pure virtual function, cannot be instantiated
class Shape { // Abstract class
public:
virtual void draw() = 0; // Pure virtual function
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void draw() { // Must implement
cout << "Drawing Circle" << endl;
}
};
// Shape s; // Error! Cannot instantiate abstract class
Circle c; // OK
Q15. What is the difference between function overloading and function overriding?
Answer:
| Function Overloading | Function Overriding |
|---|---|
| Same function name, different parameters | Same function signature in derived class |
| Compile-time polymorphism | Runtime polymorphism |
| Within same class | In inheritance hierarchy |
| No virtual keyword needed | Requires virtual in base class |
Q16. What is a constructor? Types of constructors?
Answer: Constructor is a special member function that initializes objects. Types:
- Default Constructor: No parameters
- Parameterized Constructor: Takes parameters
- Copy Constructor: Creates object from another object
- Move Constructor: C++11, transfers resources
class MyClass {
int x, y;
public:
MyClass() { x = 0; y = 0; } // Default
MyClass(int a, int b) : x(a), y(b) {} // Parameterized
MyClass(const MyClass &obj) { // Copy
x = obj.x;
y = obj.y;
}
};
Q17. What is a destructor? When is it called?
Answer: Destructor is a special member function that cleans up resources when object is destroyed.
Called when:
- Object goes out of scope
- delete is called on pointer
- Program terminates
class MyClass {
int *ptr;
public:
MyClass() {
ptr = new int[10];
}
~MyClass() { // Destructor
delete[] ptr; // Cleanup
cout << "Destructor called" << endl;
}
};
Q18. What is the difference between shallow copy and deep copy?
Answer:
- Shallow Copy: Copies pointer, both objects point to same memory
- Deep Copy: Creates new memory, copies values
// Shallow copy (default)
class Shallow {
int *data;
public:
Shallow(const Shallow &obj) {
data = obj.data; // Both point to same memory
}
};
// Deep copy
class Deep {
int *data;
public:
Deep(const Deep &obj) {
data = new int;
*data = *(obj.data); // New memory allocated
}
};
Q19. What is the difference between public, private, and protected inheritance?
Answer:
| Access Specifier | Public | Protected | Private |
|---|---|---|---|
| Public Inheritance | Public | Protected | Private |
| Protected Inheritance | Protected | Protected | Private |
| Private Inheritance | Private | Private | Private |
Q20. What is the Diamond Problem? How is it solved?
Answer: Diamond problem occurs in multiple inheritance when a class inherits from two classes that both inherit from the same base class.
class A {
public:
void func() {}
};
class B : public A {};
class C : public A {};
class D : public B, public C {
// D has two copies of A's members!
};
// Solution: Virtual inheritance
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {
// Now D has only one copy of A
};
Pointers and Memory Management (Q21-Q30)
Q21. What is a null pointer? How is it different from void pointer?
Answer:
- Null Pointer: Points to nothing (NULL or nullptr), has a type
- Void Pointer: Generic pointer, can point to any type, cannot be dereferenced directly
int *ptr = nullptr; // Null pointer
void *vptr = &x; // Void pointer
// *vptr = 10; // Error! Must cast first
*(int*)vptr = 10; // OK after casting
Q22. What is a dangling pointer? How to avoid it?
Answer: Dangling pointer points to memory that has been freed or deallocated.
int *ptr = new int(10);
delete ptr; // Memory freed
// ptr is now dangling pointer
*ptr = 20; // Undefined behavior!
// Solution: Set to nullptr after delete
delete ptr;
ptr = nullptr;
Q23. What is a smart pointer? Types of smart pointers?
Answer: Smart pointers are objects that manage memory automatically. Types:
- unique_ptr: Exclusive ownership, cannot be copied
- shared_ptr: Shared ownership, reference counted
- weak_ptr: Non-owning reference to shared_ptr
// unique_ptr
unique_ptr ptr1(new int(10));
// unique_ptr ptr2 = ptr1; // Error! Cannot copy
// shared_ptr
shared_ptr ptr3(new int(20));
shared_ptr ptr4 = ptr3; // OK, reference count = 2
// weak_ptr
weak_ptr ptr5 = ptr3; // Doesn't increase ref count
Q24. What is memory leak? How to prevent it?
Answer: Memory leak occurs when dynamically allocated memory is not freed.
Prevention:
- Always pair new with delete
- Use smart pointers
- Use RAII (Resource Acquisition Is Initialization)
- Use containers (vector, string) instead of raw arrays
Q25. What is the difference between stack and heap memory?
Answer:
| Stack | Heap |
|---|---|
| Automatic memory management | Manual memory management |
| Faster allocation | Slower allocation |
| Limited size | Larger size available |
| Local variables | Dynamic allocation (new/malloc) |
| Memory freed automatically | Must be freed manually |
Q26. What is a function pointer? Give an example.
Answer: Function pointer stores address of a function.
int add(int a, int b) {
return a + b;
}
int main() {
int (*funcPtr)(int, int) = add; // Function pointer
int result = funcPtr(5, 3); // Calls add(5, 3)
return 0;
}
Q27. What is the difference between array and pointer?
Answer:
- Array: Collection of elements, fixed size, memory allocated at compile time
- Pointer: Variable that stores address, can point to different locations
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to first element
// sizeof(arr) = 20 (5 * 4 bytes)
// sizeof(ptr) = 8 (pointer size)
// arr cannot be reassigned
// ptr can be reassigned
Q28. What is the this pointer?
Answer: this is a pointer that points to the current object instance.
class MyClass {
int x;
public:
void setX(int x) {
this->x = x; // 'this' points to current object
}
MyClass* getThis() {
return this; // Return pointer to current object
}
};
Q29. What is a void pointer? When to use it?
Answer: Void pointer can point to any data type. Use when:
- Type is unknown at compile time
- Creating generic functions
- Working with C libraries
void print(void *ptr, char type) {
switch(type) {
case 'i':
cout << *(int*)ptr << endl;
break;
case 'f':
cout << *(float*)ptr << endl;
break;
}
}
Q30. Explain pointer arithmetic in C++.
Answer: Pointer arithmetic allows operations on pointers:
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
ptr++; // Points to arr[1]
ptr += 2; // Points to arr[3]
ptr--; // Points to arr[2]
int diff = ptr - arr; // Difference = 2
Note: Arithmetic depends on data type size. For int*, incrementing moves by 4 bytes.
STL and Templates (Q31-Q40)
Q31. What is STL? Components of STL?
Answer: STL (Standard Template Library) provides reusable components. Components:
- Containers: vector, list, map, set, etc.
- Iterators: Pointers to access container elements
- Algorithms: sort, find, binary_search, etc.
- Functors: Function objects
Q32. What is the difference between vector and array?
Answer:
| Array | Vector |
|---|---|
| Fixed size | Dynamic size |
| Stack allocated | Heap allocated |
| No member functions | Rich member functions |
| No bounds checking | Bounds checking with at() |
Q33. What is the difference between map and unordered_map?
Answer:
- map: Ordered (sorted by key), implemented as BST, O(log n) operations
- unordered_map: Unordered, implemented as hash table, O(1) average operations
Q34. What is a template? Types of templates?
Answer: Template allows writing generic code. Types:
- Function Template: Generic function
- Class Template: Generic class
// Function template
template
T maximum(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template
class Stack {
T *arr;
// ...
};
Q35. What is the difference between typename and class in templates?
Answer: In template declarations, typename and class are interchangeable. However, typename must be used for dependent types.
template // OK
template // Also OK, same meaning
template
class MyClass {
typename T::iterator it; // 'typename' required here
};
Q36. What is template specialization?
Answer: Template specialization provides specific implementation for particular types.
template
void print(T t) {
cout << t << endl;
}
// Specialization for char*
template <>
void print(char* s) {
cout << "String: " << s << endl;
}
Q37. What is an iterator? Types of iterators?
Answer: Iterator is an object that points to elements in a container. Types:
- Input Iterator: Read-only, forward only
- Output Iterator: Write-only, forward only
- Forward Iterator: Read/write, forward only
- Bidirectional Iterator: Can move backward
- Random Access Iterator: Can jump to any position
Q38. What is the difference between set and multiset?
Answer:
- set: Stores unique elements only
- multiset: Allows duplicate elements
set s;
s.insert(10);
s.insert(10); // Only one 10 stored
multiset ms;
ms.insert(10);
ms.insert(10); // Two 10s stored
Q39. What is RAII?
Answer: RAII (Resource Acquisition Is Initialization) is a programming idiom where resources are acquired in constructor and released in destructor.
class FileHandler {
FILE *file;
public:
FileHandler(const char* name) {
file = fopen(name, "r"); // Acquire resource
}
~FileHandler() {
fclose(file); // Release resource automatically
}
};
Q40. What is the difference between list and vector?
Answer:
| Vector | List |
|---|---|
| Dynamic array | Doubly linked list |
| Random access (O(1)) | Sequential access (O(n)) |
| Insertion/deletion at end: O(1) | Insertion/deletion: O(1) |
| Cache friendly | Not cache friendly |
Advanced Topics (Q41-Q50)
Q41. What is exception handling in C++?
Answer: Exception handling manages runtime errors using try, catch, and throw.
try {
int x = 10, y = 0;
if (y == 0)
throw "Division by zero!";
int result = x / y;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}
Q42. What is the difference between throw, throw with object, and rethrow?
Answer:
- throw: Rethrows current exception
- throw object: Throws new exception
- throw with expression: Throws exception with value
Q43. What is operator overloading? Give an example.
Answer: Operator overloading allows defining behavior for operators with user-defined types.
class Complex {
int real, imag;
public:
Complex operator+(const Complex &c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
};
Q44. What is a friend function? What are its limitations?
Answer: Friend function can access private and protected members of a class.
Limitations:
- Not a member function
- Cannot be inherited
- Cannot use this pointer
- Violates encapsulation
Q45. What is the difference between static and dynamic binding?
Answer:
- Static Binding: Resolved at compile time (function overloading)
- Dynamic Binding: Resolved at runtime (virtual functions)
Q46. What is a virtual destructor? Why is it needed?
Answer: Virtual destructor ensures proper cleanup when deleting object through base pointer.
class Base {
public:
virtual ~Base() { // Virtual destructor
cout << "Base destructor" << endl;
}
};
class Derived : public Base {
public:
~Derived() {
cout << "Derived destructor" << endl;
}
};
Base *ptr = new Derived();
delete ptr; // Calls both destructors due to virtual
Q47. What is RTTI (Runtime Type Information)?
Answer: RTTI allows determining object type at runtime using typeid and dynamic_cast.
Base *ptr = new Derived();
if (Derived *d = dynamic_cast(ptr)) {
// Successful cast
}
cout << typeid(*ptr).name() << endl; // Type name
Q48. What is the difference between new and new[]?
Answer:
- new: Allocates single object, use
delete - new[]: Allocates array, use
delete[]
Q49. What is the volatile keyword?
Answer: volatile tells compiler that variable value may change unexpectedly (e.g., by hardware). Prevents compiler optimizations.
volatile int flag = 0;
while (flag == 0) {
// Compiler won't optimize this loop
// because flag is volatile
}
Q50. What is the difference between inline function and macro?
Answer:
| Inline Function | Macro |
|---|---|
| Type checking done | No type checking |
| Evaluates arguments once | May evaluate multiple times |
| Can be debugged | Cannot be debugged |
| Respects scope | Doesn't respect scope |
Interview Tips
Preparation Tips
- Practice Coding: Write code for each concept, don't just read
- Understand Deeply: Know the "why" behind each concept
- Solve Problems: Practice on platforms like LeetCode, HackerRank
- Mock Interviews: Practice explaining concepts out loud
- Review Basics: Strong fundamentals are more important than advanced topics
During the Interview
- Think Aloud: Explain your thought process
- Ask Questions: Clarify requirements before coding
- Start Simple: Begin with basic solution, then optimize
- Handle Edge Cases: Consider boundary conditions
- Stay Calm: It's okay to not know everything
Common Mistakes to Avoid
- Memorizing answers without understanding
- Not practicing coding problems
- Ignoring memory management questions
- Forgetting about STL containers and algorithms
- Not preparing for system design questions
Sign up here with your email
ConversionConversion EmoticonEmoticon