C++

C++

Top Interview Questions

About C++

 

Understanding C++

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.


History of C++

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.


What is C++?

C++ is a multi-paradigm programming language, meaning it supports multiple styles of programming:

  1. Procedural Programming: Using functions and procedures, similar to C.

  2. Object-Oriented Programming (OOP): Classes, objects, encapsulation, inheritance, and polymorphism.

  3. 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.


Features of C++

C++ is known for its rich set of features, which provide flexibility and power:

  1. Object-Oriented Programming (OOP): Supports encapsulation, inheritance, polymorphism, and abstraction.

  2. Low-Level Manipulation: Allows direct memory management using pointers, making it ideal for system programming.

  3. Performance: Compiled code executes faster compared to interpreted languages.

  4. Portability: Programs can be compiled on multiple platforms with minimal changes.

  5. Standard Template Library (STL): Provides reusable data structures (like vectors, stacks, queues) and algorithms.

  6. Extensibility: Users can define their own data types, operators, and functions.

  7. Rich Library Support: Offers both standard libraries and third-party frameworks for graphics, networking, and more.


Core Concepts of C++

1. Variables and Data Types

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.


2. Control 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.


3. Functions

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.


4. Object-Oriented Programming (OOP)

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.


5. Pointers and Memory Management

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.


6. Templates and Generic Programming

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.


7. Standard Template Library (STL)

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.


Advantages of C++

  1. High Performance: Suitable for system programming and applications requiring speed.

  2. Cross-Platform: Can be compiled on Windows, Linux, macOS, and embedded systems.

  3. Versatile: Supports procedural, object-oriented, and generic programming.

  4. Rich Ecosystem: STL, third-party libraries, and community support.

  5. System-Level Programming: Ability to manipulate memory and hardware resources.

  6. Industry Standard: Used in software development, embedded systems, gaming, and finance.


Disadvantages of C++

  1. Complex Syntax: Steeper learning curve for beginners compared to languages like Python.

  2. Manual Memory Management: Risk of memory leaks and dangling pointers.

  3. No Built-In Garbage Collection: Unlike Java or C#.

  4. Error-Prone: Small mistakes can lead to segmentation faults or undefined behavior.


Applications of C++

C++ is highly versatile and used in multiple domains:

  1. System Software: Operating systems, device drivers, and file systems.

  2. Game Development: Unreal Engine and graphics-intensive games rely heavily on C++.

  3. Embedded Systems: IoT devices, robotics, and automotive software.

  4. Finance: High-frequency trading platforms and banking software.

  5. GUI Applications: Desktop applications like Adobe Photoshop and Microsoft Office components.

  6. Scientific Computing: Simulations, data analysis, and high-performance computing.


Modern C++ and Standards

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.


Conclusion

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.

Fresher Interview Questions

 

1. Basics of C++

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

2. Data Types & Variables

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


3. Functions in C++

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)

4. Object-Oriented Concepts in C++

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

5. Memory Management

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."


6. Templates

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


7. Exception Handling

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


8. Standard Template Library (STL)

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


9. Miscellaneous & Scenario-Based

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

Experienced Interview Questions

 

Basic Concepts

1. What are the basic features of C++?

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


2. Difference between C and C++?

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

3. What is the difference between reference and pointer in C++?

Answer:

Feature Pointer Reference
Memory Stores address Alias for variable
Null allowed Yes No
Reassignment Can reassign Cannot reassign
Syntax *ptr &ref

4. What are inline functions?

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.


5. What are constructors and destructors in C++?

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"; }
};

6. Explain the difference between stack and heap memory in C++.

Answer:

Feature Stack Heap
Allocation Automatic Dynamic
Lifetime Scoped Until delete/free
Speed Faster Slower
Size Limited Larger

7. Difference between shallow copy and deep copy?

Answer:

  • Shallow copy: Copies values including pointers; both objects share same memory.

  • Deep copy: Allocates new memory for pointer members; objects independent.


8. What is the difference between 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

9. What is the difference between delete and delete[]?

Answer:

  • delete – frees memory allocated for single object

  • delete[] – frees memory allocated for arrays


10. What are namespaces?

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); }

OOP Concepts

11. Explain encapsulation in C++.

Answer:

  • Wrapping data (attributes) and methods together, restricting direct access.

  • Implemented using private/protected members and public getters/setters.


12. Explain inheritance types in C++.

Answer:

  1. Public: Public members remain public, protected remain protected

  2. Private: Public/protected members become private

  3. Protected: Public/protected members become protected

  • Multiple inheritance is supported in C++


13. Explain polymorphism 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"

14. What is an abstract class?

Answer:

  • Class with at least one pure virtual function

  • Cannot instantiate

class Shape { virtual void draw()=0; };

15. Difference between virtual, pure virtual, and non-virtual functions?

Answer:

Function Definition Overridable?
Non-virtual Normal function Compile-time binding
Virtual Declared virtual Runtime binding
Pure virtual =0 Must override; abstract class

16. What is operator overloading? Give an example.

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); }
};

17. What is the difference between friend function and member function?

Answer:

  • Friend function: Non-member; can access private/protected members

  • Member function: Part of class


18. Explain the difference between function overloading and function overriding.

Answer:

  • Overloading: Same function name, different signature, compile-time polymorphism

  • Overriding: Subclass provides implementation of base class virtual function, runtime polymorphism


19. What are virtual destructors and why are they used?

Answer:

  • Ensures proper cleanup of derived class objects when deleted via base class pointer

class Base { virtual ~Base(){} };

20. Difference between abstract class and interface in C++?

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)


Advanced Features

21. Explain templates in C++.

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; };

22. Difference between class template and function template?

Answer:

  • Function template: Generic function

  • Class template: Generic class with member functions/variables


23. What is STL (Standard Template Library)?

Answer:

  • Collection of template classes for common data structures (vector, list, map) and algorithms

  • Components: Containers, Algorithms, Iterators, Function Objects


24. Explain containers in STL.

Answer:

  • Sequence containers: vector, list, deque

  • Associative containers: set, map, multiset, multimap

  • Unordered containers: unordered_map, unordered_set

  • Container adapters: stack, queue, priority_queue


25. Explain iterators in STL.

Answer:

  • Objects that point to elements in a container

  • Types: input, output, forward, bidirectional, random-access

  • Used for generic algorithms


26. What are smart pointers in C++11?

Answer:

  • Automatic memory management

  • Types:

    • unique_ptr – sole ownership

    • shared_ptr – shared ownership

    • weak_ptr – avoids cyclic references


27. Difference between std::vector and std::list?

Answer:

Feature vector list
Memory Contiguous Non-contiguous
Access Random Sequential
Insert/Delete Slow middle insert Fast middle insert

28. Explain RAII in C++.

Answer:

  • Resource Acquisition Is Initialization

  • Encapsulates resource management in objects; destructor frees resource automatically

  • Example: std::lock_guard for mutexes


29. Difference between const, constexpr, and mutable?

Answer:

  • const – variable cannot change

  • constexpr – compile-time constant

  • mutable – member variable modifiable even in const objects


30. Difference between new/delete and malloc/free revisited.

Answer:

  • new/delete calls constructor/destructor, type-safe

  • malloc/free only allocates memory, no constructor call


Memory Management

31. What is memory leak and how to avoid?

Answer:

  • Memory allocated dynamically but not freed → leak

  • Avoid using smart pointers, delete dynamically allocated memory, avoid dangling pointers


32. What is dangling pointer?

Answer:

  • Pointer pointing to freed memory

  • Solution: Set pointer to nullptr after deletion


33. Difference between stack and heap memory with examples?

Answer:

  • Stack: Local variables

  • Heap: new allocation

  • Stack faster, limited size; heap slower, flexible


34. Explain segmentation fault in C++.

Answer:

  • Accessing invalid memory location (e.g., dereferencing null pointer)


35. Difference between static and dynamic polymorphism?

Answer:

  • Static: Function overloading, templates

  • Dynamic: Virtual functions, runtime binding


Practical / Scenario-Based

36. How do you implement a singleton class in C++?

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; } 
};

37. How do you handle multiple inheritance ambiguity?

Answer:

  • Use virtual inheritance

class A {}; class B : virtual public A {}; class C : virtual public A {};

38. How do you implement event callbacks in C++?

Answer:

  • Function pointers, functors, or std::function with std::bind


39. Explain move semantics in C++11.

Answer:

  • Optimizes resource transfer instead of copying

  • Use rvalue references (T&&)

  • Reduces overhead in large objects


40. Explain C++11 features you have used.

Answer:

  • Auto type deduction (auto x=5;)

  • Range-based for loops

  • Lambda expressions

  • Smart pointers

  • nullptr instead of NULL

  • Move semantics


41. How do you optimize a large-scale C++ project?

Answer:

  • Use RAII and smart pointers

  • Minimize unnecessary copies

  • Use move semantics

  • Proper memory management

  • Efficient STL containers and algorithms

  • Compile-time constants (constexpr)