Top Interview Questions
C++ is a general-purpose programming language that combines the features of both high-level and low-level languages. Developed as an extension of the C programming language by Bjarne Stroustrup in 1983, C++ was designed to provide object-oriented capabilities while retaining the efficiency and performance of C.
C++ is widely used in software development, systems programming, game development, and applications requiring high performance and resource control. Its versatility, speed, and powerful features make it a preferred language for developers dealing with complex systems.
C++ evolved from the C language, which was developed in the early 1970s for system programming. Bjarne Stroustrup, working at Bell Labs, aimed to create a language that combined C’s efficiency with high-level abstractions for easier programming.
Key milestones in C++ history include:
1979: The “C with Classes” prototype was developed.
1983: The language was officially named C++, indicating the incremental improvement (“++” in C represents increment).
1985: First edition of “The C++ Programming Language” was published.
1990: ANSI standardization efforts began.
1998: ISO published the first standardized version, known as C++98.
2011, 2014, 17, 20, 23: Modern versions introduced features like auto keyword, smart pointers, lambda expressions, concurrency support, and concepts.
C++ is a multi-paradigm programming language, meaning it supports multiple styles of programming:
Procedural Programming: Using functions and procedures, similar to C.
Object-Oriented Programming (OOP): Classes, objects, encapsulation, inheritance, and polymorphism.
Generic Programming: Using templates to write code that works with any data type.
By combining these paradigms, C++ enables developers to write efficient, reusable, and scalable code.
C++ is known for its rich set of features, which provide flexibility and power:
Object-Oriented Programming (OOP): Supports encapsulation, inheritance, polymorphism, and abstraction.
Low-Level Manipulation: Allows direct memory management using pointers, making it ideal for system programming.
Performance: Compiled code executes faster compared to interpreted languages.
Portability: Programs can be compiled on multiple platforms with minimal changes.
Standard Template Library (STL): Provides reusable data structures (like vectors, stacks, queues) and algorithms.
Extensibility: Users can define their own data types, operators, and functions.
Rich Library Support: Offers both standard libraries and third-party frameworks for graphics, networking, and more.
C++ supports a variety of primitive data types:
int – integer values
float – floating-point numbers
double – double-precision floating-point numbers
char – single characters
bool – boolean values (true or false)
It also supports derived data types like arrays, pointers, references, and structures.
C++ uses decision-making and loops to control program flow:
Conditional statements: if, else, switch
Loops: for, while, do-while
Jump statements: break, continue, return, goto
These features make it possible to create complex, logical workflows efficiently.
Functions in C++ are blocks of reusable code that perform specific tasks. Functions help in:
Code reusability
Modularity
Easier debugging and maintenance
C++ also supports function overloading, allowing multiple functions with the same name but different parameters.
C++ supports OOP principles:
Class: A blueprint for creating objects.
Object: An instance of a class.
Encapsulation: Hides data using private/protected access modifiers.
Inheritance: Allows a class to inherit properties and methods from another class.
Polymorphism: Enables a function or object to behave differently in different contexts.
C++ provides direct control over memory through pointers. Pointers store memory addresses of variables and are essential for:
Dynamic memory allocation (new and delete)
Efficient data structures (linked lists, trees, graphs)
System-level programming
This low-level capability gives C++ a performance advantage over many high-level languages.
C++ supports templates, which allow functions and classes to operate with any data type:
template <typename T>
T add(T a, T b) {
return a + b;
}
Templates enhance code reusability and type safety.
STL provides predefined classes and functions for common data structures and algorithms:
Containers: vector, list, map, set
Algorithms: sort, search, binary_search
Iterators: Abstract way to traverse data structures
STL significantly reduces development time for complex applications.
High Performance: Suitable for system programming and applications requiring speed.
Cross-Platform: Can be compiled on Windows, Linux, macOS, and embedded systems.
Versatile: Supports procedural, object-oriented, and generic programming.
Rich Ecosystem: STL, third-party libraries, and community support.
System-Level Programming: Ability to manipulate memory and hardware resources.
Industry Standard: Used in software development, embedded systems, gaming, and finance.
Complex Syntax: Steeper learning curve for beginners compared to languages like Python.
Manual Memory Management: Risk of memory leaks and dangling pointers.
No Built-In Garbage Collection: Unlike Java or C#.
Error-Prone: Small mistakes can lead to segmentation faults or undefined behavior.
C++ is highly versatile and used in multiple domains:
System Software: Operating systems, device drivers, and file systems.
Game Development: Unreal Engine and graphics-intensive games rely heavily on C++.
Embedded Systems: IoT devices, robotics, and automotive software.
Finance: High-frequency trading platforms and banking software.
GUI Applications: Desktop applications like Adobe Photoshop and Microsoft Office components.
Scientific Computing: Simulations, data analysis, and high-performance computing.
Modern C++ (C++11, C++14, C++17, C++20, C++23) introduces features that simplify development:
Auto keyword: Type inference
Lambda functions: Anonymous, inline functions
Smart pointers: Automatic memory management
Concurrency support: Multi-threading capabilities
Concepts and Modules: Better type checking and modular code
These features improve productivity, safety, and code readability while retaining C++’s core efficiency.
C++ is a powerful, versatile, and high-performance programming language that bridges low-level system programming and high-level application development. Its combination of procedural, object-oriented, and generic programming paradigms allows developers to create software ranging from operating systems to cutting-edge games and scientific simulations.
Despite its learning curve and manual memory management challenges, C++ remains indispensable for applications where performance, resource control, and scalability are critical. Modern C++ continues to evolve, making it a reliable and future-proof language for developers and enterprises alike.
Q1. What is C++?
Answer:
"C++ is a general-purpose, high-level programming language developed by Bjarne Stroustrup in 1983. It supports procedural, object-oriented, and generic programming, making it versatile for system/software development."
Q2. What are the key features of C++?
Answer:
Supports Object-Oriented Programming
Low-level memory manipulation (pointers)
Rich Standard Template Library (STL)
Function and operator overloading
Supports inheritance, polymorphism, and encapsulation
Q3. Difference between C and C++
| Feature | C | C++ |
|---|---|---|
| Paradigm | Procedural | Multi-paradigm (OOP + Procedural) |
| Data Encapsulation | Not supported | Supported (Classes) |
| Function Overloading | Not allowed | Allowed |
| Standard Library | Limited | Rich STL & OOP libraries |
| Namespace support | No | Yes |
Q4. What is a namespace in C++?
Answer:
"Namespace is a declarative region that provides scope to identifiers (variables, functions, classes) to avoid name conflicts."
Example:
namespace MySpace {
int value = 10;
}
using namespace MySpace;
cout << value; // Output: 10
Q5. What is the difference between C++ and Java?
| Feature | C++ | Java |
|---|---|---|
| Memory Management | Manual (pointers) | Automatic (Garbage Collection) |
| Multiple Inheritance | Supported | Not supported (interfaces) |
| Platform Dependency | Compiled for OS | Platform independent via JVM |
| Pointers | Supported | Not supported |
Q6. What are different data types in C++?
Primitive types: int, char, float, double, bool
Derived types: arrays, pointers, references
User-defined types: class, struct, enum, typedef
Void type: no value
Q7. What is the difference between pointer and reference?
| Feature | Pointer | Reference |
|---|---|---|
| Null value | Can be null | Cannot be null |
| Re-assignment | Can point to another variable | Cannot be reassigned |
| Syntax | *ptr | &ref |
Q8. What is a constant pointer vs pointer to a constant?
Constant pointer: pointer itself cannot change
Pointer to constant: value pointed to cannot change
Example:
int a=10, b=20;
const int* ptr = &a; // Value cannot change
int* const ptr2 = &a; // Pointer cannot change
Q9. What is the difference between stack and heap memory?
Stack: Automatic memory allocation, fast, destroyed after scope ends
Heap: Dynamic allocation using new/delete, manual management
Q10. What is typecasting in C++?
Answer:
"Typecasting converts a variable from one data type to another."
Static cast: compile-time conversion
Dynamic cast: runtime check for polymorphic types
Const cast: modifies constness
Reinterpret cast: low-level reinterpretation
Q11. What is a function in C++?
"A function is a block of code that performs a specific task and can be reused multiple times."
Q12. What is function overloading?
"Function overloading allows multiple functions with the same name but different parameters."
Example:
int add(int a,int b){ return a+b; }
double add(double a,double b){ return a+b; }
Q13. What is inline function?
Answer:
"Inline functions reduce function call overhead by replacing the call with the function code at compile time using the inline keyword."
Q14. What is recursion?
Answer:
"Recursion is when a function calls itself either directly or indirectly to solve a problem."
Example: Factorial:
int factorial(int n){ return (n<=1)?1:n*factorial(n-1);}
Q15. What is the difference between call by value and call by reference?
| Feature | Call by Value | Call by Reference |
|---|---|---|
| Copy of variable | Yes | No (original modified) |
| Memory usage | Less efficient for large objects | More efficient |
| Syntax | void func(int a) |
void func(int &a) |
Q16. What is a class and object in C++?
Class: Blueprint for creating objects
Object: Instance of a class
Q17. What is encapsulation?
"Encapsulation is wrapping data members and methods in a class and controlling access using access specifiers."
Q18. What is inheritance in C++?
"Inheritance allows a class to derive properties and behavior from another class, supporting code reuse."
Types: public, private, protected inheritance
Q19. What is polymorphism in C++?
"Polymorphism allows a single interface to represent different types of actions."
Compile-time: Function/Operator overloading
Run-time: Virtual functions (method overriding)
Q20. What is abstraction?
"Abstraction hides implementation details using abstract classes (pure virtual functions) so that users only see the interface."
Q21. What is a virtual function?
"A virtual function allows a derived class to override it and supports runtime polymorphism."
Example:
class Base{ virtual void show(){} };
class Derived: public Base{ void show(){} };
Q22. What is a pure virtual function?
"A function with =0 in a base class; makes the class abstract and cannot be instantiated."
Q23. Difference between compile-time and runtime polymorphism?
| Feature | Compile-time | Runtime |
|---|---|---|
| Example | Function overloading | Virtual functions |
| Resolution | During compilation | During runtime |
| Performance | Faster | Slightly slower |
Q24. Difference between new and malloc()
| Feature | new | malloc() |
|---|---|---|
| Language | C++ only | C and C++ |
| Constructor | Calls constructor | No constructor |
| Return type | Correct type | void* |
| Exception on failure | Throws bad_alloc |
Returns NULL |
Q25. Difference between delete and free()
delete: Calls destructor, C++ only
free(): C function, only frees memory
Q26. What are pointers in C++?
"Pointer is a variable that stores the memory address of another variable."
Q27. What is a reference in C++?
"Reference is an alias for an existing variable, used to pass data without copying."
Q28. What is smart pointer?
"Smart pointers manage memory automatically using RAII (Resource Acquisition Is Initialization). Examples: unique_ptr, shared_ptr, weak_ptr."
Q29. What are templates in C++?
"Templates allow writing generic functions or classes to work with any data type."
Example:
template<typename T>
T add(T a, T b){ return a+b; }
Q30. Difference between function template and class template?
Function template: Generic function
Class template: Generic class
Q31. How do you handle exceptions in C++?
"Using try, catch, and throw keywords."
Example:
try { throw 10; }
catch(int e) { cout << "Error: " << e; }
Q32. What is the difference between throw and noexcept?
throw: Used to raise exceptions
noexcept: Indicates function does not throw exceptions
Q33. What is STL in C++?
"STL provides ready-to-use generic classes and functions for containers, algorithms, and iterators."
Q34. Name the types of containers in STL
Sequence: vector, list, deque
Associative: set, map, multimap
Unordered: unordered_set, unordered_map
Q35. What is an iterator in STL?
"Iterator provides a way to access elements of a container sequentially without exposing underlying representation."
Q36. Difference between vector and array in C++
| Feature | Vector | Array |
|---|---|---|
| Size | Dynamic | Fixed |
| Memory Management | Managed internally | Manual |
| Functions | push_back(), pop_back() | None |
Q37. Difference between map and unordered_map
map: Ordered, implemented as balanced tree
unordered_map: Unordered, implemented as hash table, faster access
Q38. What is RAII in C++?
"Resource Acquisition Is Initialization: objects acquire resources in constructor and release in destructor to prevent leaks."
Q39. What is the difference between shallow copy and deep copy?
Shallow copy: Copies object but references same dynamic memory
Deep copy: Creates a new copy of dynamic memory
Q40. Difference between struct and class in C++
| Feature | struct | class |
|---|---|---|
| Default access | Public | Private |
| OOP support | Yes | Yes |
Q41. Difference between public, private, and protected inheritance
Public: public → public, protected → protected
Protected: public/protected → protected
Private: public/protected → private
Q42. What is a friend function?
"Friend function can access private and protected members of a class without being a member."
Q43. What is the difference between == and = in C++?
=: Assignment operator
==: Equality comparison operator
Q44. Difference between compile-time and runtime in C++
Compile-time: Errors detected before execution
Runtime: Errors occur during program execution
Q45. Why is C++ still used in industry?
System programming, game development, embedded systems
Performance-critical applications
OOP support for large-scale applications
Answer:
Object-Oriented: Supports classes, objects, encapsulation, inheritance, polymorphism
Rich Standard Library: STL, I/O, algorithms
Memory Management: Supports dynamic allocation (new/delete)
Low-Level Manipulation: Pointers, references, and hardware-level access
Compiled Language: Efficient and fast execution
Answer:
| Feature | C | C++ |
|---|---|---|
| Paradigm | Procedural | Object-Oriented + Procedural |
| Data hiding | No | Yes (classes, private/protected) |
| Function overloading | No | Yes |
| Memory management | malloc/free | new/delete |
| Exception handling | No | Yes |
Answer:
| Feature | Pointer | Reference |
|---|---|---|
| Memory | Stores address | Alias for variable |
| Null allowed | Yes | No |
| Reassignment | Can reassign | Cannot reassign |
| Syntax | *ptr |
&ref |
Answer:
Functions suggested to the compiler for inline expansion to reduce call overhead.
Syntax:
inline int add(int a, int b) { return a + b; }
Benefits: Faster execution, but increases code size.
Answer:
Constructor: Initializes object; called automatically. Can be default, parameterized, or copy constructor.
Destructor: Cleans up resources when object goes out of scope; called automatically.
class Example {
public: Example(){ cout << "Constructor"; }
~Example(){ cout << "Destructor"; }
};
Answer:
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Dynamic |
| Lifetime | Scoped | Until delete/free |
| Speed | Faster | Slower |
| Size | Limited | Larger |
Answer:
Shallow copy: Copies values including pointers; both objects share same memory.
Deep copy: Allocates new memory for pointer members; objects independent.
new and malloc()?Answer:
| Feature | new | malloc() |
|---|---|---|
| Type safety | Yes | No |
| Constructor call | Yes | No |
| Deallocation | delete | free() |
| Throws exception | Yes (if fail) | Returns NULL |
delete and delete[]?Answer:
delete – frees memory allocated for single object
delete[] – frees memory allocated for arrays
Answer:
Avoid naming conflicts in large projects.
Example:
namespace Math { int add(int a,int b){return a+b;} }
int main() { cout << Math::add(2,3); }
Answer:
Wrapping data (attributes) and methods together, restricting direct access.
Implemented using private/protected members and public getters/setters.
Answer:
Public: Public members remain public, protected remain protected
Private: Public/protected members become private
Protected: Public/protected members become protected
Multiple inheritance is supported in C++
Answer:
Compile-time (Static): Function overloading, operator overloading
Run-time (Dynamic): Virtual functions
class Base { virtual void show(){ cout<<"Base"; } };
class Derived: public Base { void show(){ cout<<"Derived"; } };
Base* b = new Derived(); b->show(); // Prints "Derived"
Answer:
Class with at least one pure virtual function
Cannot instantiate
class Shape { virtual void draw()=0; };
Answer:
| Function | Definition | Overridable? |
|---|---|---|
| Non-virtual | Normal function | Compile-time binding |
| Virtual | Declared virtual |
Runtime binding |
| Pure virtual | =0 |
Must override; abstract class |
Answer:
Defining custom behavior for operators in user-defined types.
class Complex {
int r,i;
public: Complex(int a,int b){r=a;i=b;}
Complex operator+(Complex c){ return Complex(r+c.r, i+c.i); }
};
Answer:
Friend function: Non-member; can access private/protected members
Member function: Part of class
Answer:
Overloading: Same function name, different signature, compile-time polymorphism
Overriding: Subclass provides implementation of base class virtual function, runtime polymorphism
Answer:
Ensures proper cleanup of derived class objects when deleted via base class pointer
class Base { virtual ~Base(){} };
Answer:
Abstract class: Can have data members, concrete methods, pure virtual methods
Interface (conceptually): Only pure virtual methods (C++ uses abstract class to implement interface)
Answer:
Generic programming
Function template:
template <typename T> T add(T a,T b){ return a+b; }
Class template:
template <class T> class Box { T item; };
Answer:
Function template: Generic function
Class template: Generic class with member functions/variables
Answer:
Collection of template classes for common data structures (vector, list, map) and algorithms
Components: Containers, Algorithms, Iterators, Function Objects
Answer:
Sequence containers: vector, list, deque
Associative containers: set, map, multiset, multimap
Unordered containers: unordered_map, unordered_set
Container adapters: stack, queue, priority_queue
Answer:
Objects that point to elements in a container
Types: input, output, forward, bidirectional, random-access
Used for generic algorithms
Answer:
Automatic memory management
Types:
unique_ptr – sole ownership
shared_ptr – shared ownership
weak_ptr – avoids cyclic references
std::vector and std::list?Answer:
| Feature | vector | list |
|---|---|---|
| Memory | Contiguous | Non-contiguous |
| Access | Random | Sequential |
| Insert/Delete | Slow middle insert | Fast middle insert |
Answer:
Resource Acquisition Is Initialization
Encapsulates resource management in objects; destructor frees resource automatically
Example: std::lock_guard for mutexes
const, constexpr, and mutable?Answer:
const – variable cannot change
constexpr – compile-time constant
mutable – member variable modifiable even in const objects
new/delete and malloc/free revisited.Answer:
new/delete calls constructor/destructor, type-safe
malloc/free only allocates memory, no constructor call
Answer:
Memory allocated dynamically but not freed → leak
Avoid using smart pointers, delete dynamically allocated memory, avoid dangling pointers
Answer:
Pointer pointing to freed memory
Solution: Set pointer to nullptr after deletion
Answer:
Stack: Local variables
Heap: new allocation
Stack faster, limited size; heap slower, flexible
Answer:
Accessing invalid memory location (e.g., dereferencing null pointer)
Answer:
Static: Function overloading, templates
Dynamic: Virtual functions, runtime binding
Answer:
Private constructor, static method to get instance, delete copy constructor and assignment operator
class Singleton {
static Singleton* instance;
private: Singleton(){}
public: static Singleton* getInstance(){ if(!instance) instance=new Singleton(); return instance; }
};
Answer:
Use virtual inheritance
class A {}; class B : virtual public A {}; class C : virtual public A {};
Answer:
Function pointers, functors, or std::function with std::bind
Answer:
Optimizes resource transfer instead of copying
Use rvalue references (T&&)
Reduces overhead in large objects
Answer:
Auto type deduction (auto x=5;)
Range-based for loops
Lambda expressions
Smart pointers
nullptr instead of NULL
Move semantics
Answer:
Use RAII and smart pointers
Minimize unnecessary copies
Use move semantics
Proper memory management
Efficient STL containers and algorithms
Compile-time constants (constexpr)