C++ 200 QUESTIONS BY CHATGPT
Section 1 – Core C++ Concepts (Q1–Q40)
Q1. What is C++?
Answer:
C++ is a general-purpose, object-oriented programming language created by Bjarne
Stroustrup in 1983.
It extends C by adding OOP features while still supporting low-level memory
manipulation.
Used in game engines, operating systems, embedded systems, competitive
programming.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!";
return 0;
Q2. Di erence between C and C++
Feature C C++
Paradigm Procedural Multi-paradigm (OOP + Procedural)
OOP Support No Yes
Function Overloading No Yes
Encapsulation No Yes
Q3. Access Specifiers in C++
Answer: Control visibility of class members.
public → anywhere
private → only inside the class
protected → inside class & derived classes
class Example {
public:
int a;
private:
int b;
protected:
int c;
};
Q4. Pass by Value vs Pass by Reference
Pass by Value: Copy sent → changes not reflected.
Pass by Reference: Original sent → changes reflected.
void val(int x) { x = 10; }
void ref(int &x) { x = 10; }
Q5. Pointer vs Reference
Feature Pointer Reference
Can be NULL? Yes No
Reassignable? Yes No
Syntax *p &r
Q6. Inline Functions
Small functions → avoid function call overhead.
inline int square(int x) { return x * x; }
Q7. const vs #define
const → type-safe, scoped.
#define → preprocessor macro.
Q8. Type Casting
int a = 5;
double b = static_cast<double>(a);
static_cast, dynamic_cast, const_cast, reinterpret_cast.
Q9. Namespaces
Avoids naming conflicts.
namespace MySpace {
void hello() { cout << "Hi"; }
Q10. Lvalue & Rvalue
Lvalue → has a persistent address.
Rvalue → temporary.
Q11. Static Variables
Retain value between function calls.
void counter() {
static int count = 0;
count++;
cout << count;
Q12. Friend Functions
Allow non-member functions to access private data.
class Test {
int x;
public:
friend void show(Test);
};
Q13. Function Overloading
Same function name, di erent parameters.
int add(int a, int b) { return a+b; }
double add(double a, double b) { return a+b; }
Q14. Default Arguments
Provide default values for parameters.
int sum(int a, int b=5) { return a+b; }
Q15. Function Pointers
Store address of a function.
void hello() { cout << "Hi"; }
void (*fp)() = hello;
Q16. Enumerations
Define named integer constants.
enum Color { Red, Green, Blue };
Q17. Scope Resolution Operator ::
Access global variables or class members.
Q18. Volatile Keyword
Tells compiler not to optimize a variable.
Q19. Preprocessor Directives
#include, #define, #ifdef, #pragma.
Q20. Macros vs Inline Functions
Macros → replaced before compilation.
Inline → function call replaced during compilation.
Q21. What is a constructor in C++?
Answer: A special member function with the same name as the class,
automatically called when an object is created.
class Demo {
public:
Demo() { cout << "Constructor called"; }
};
Types: Default, Parameterized, Copy.
Q22. Destructor
Answer: Called automatically when an object goes out of scope to clean up
resources.
~Demo() { cout << "Destructor called"; }
Q23. Copy Constructor
Answer: Creates a new object as a copy of an existing object.
Demo(const Demo &obj) { }
Q24. Shallow Copy vs Deep Copy
Shallow Copy: Copies pointers without duplicating memory → can cause double
deletion.
Deep Copy: Allocates new memory and copies content.
Q25. Operator Overloading
Answer: Gives new meaning to operators for user-defined types.
class Complex {
public:
int r, i;
Complex operator + (Complex c) {
return {r + c.r, i + c.i};
};
Q26. Overloading << and >>
friend ostream& operator<<(ostream& out, const Demo& d);
friend istream& operator>>(istream& in, Demo& d);
Q27. this Pointer
Answer: Points to the current object of a class.
Q28. Static Member Functions
Accessible without creating an object.
static void show() { }
Q29. mutable Keyword
Allows modification of a member in a const object.
Q30. const Member Functions
Cannot modify class data members.
int get() const { return x; }
Q31. Function Templates
Generic functions for multiple data types.
template <typename T>
T add(T a, T b) { return a + b; }
Q32. Class Templates
Generic classes.
template <class T>
class Demo { T data; };
Q33. Explicit Keyword
Prevents implicit type conversions in constructors.
Q34. Friend Class
One class can access private members of another.
Q35. typedef vs using
typedef → C-style type alias.
using → C++11 type alias.
Q36. nullptr in C++11
Safer null pointer constant than NULL.
Q37. auto Keyword
Type deduced at compile time.
Q38. decltype Keyword
Gets the type of an expression.
Q39. Range-based for Loop
for(auto x : arr) { cout << x; }
Q40. Lambda Functions
Anonymous functions introduced in C++11.
auto sum = [](int a, int b) { return a + b; };
Section 2 – OOP Advanced (Q41–Q80)
Q41. What are the four main pillars of OOP?
Answer:
1. Encapsulation – Wrapping data & functions in a class.
2. Abstraction – Showing only essential features, hiding internal details.
3. Inheritance – Acquiring properties & behavior from another class.
4. Polymorphism – One name, many forms (function/operator overloading, virtual
functions).
Q42. What is Inheritance in C++?
Answer: Mechanism by which a class (derived) can acquire properties & methods of
another class (base).
class A { };
class B : public A { }; // B inherits from A
Q43. Types of Inheritance in C++
Single
Multiple
Multilevel
Hierarchical
Hybrid
Q44. What is Multiple Inheritance?
Answer: A class inherits from more than one base class.
class A { };
class B { };
class C : public A, public B { };
Q45. Diamond Problem in Multiple Inheritance
Occurs when a derived class inherits from two classes that share a common base
class, leading to ambiguity.
Q46. Virtual Inheritance
Answer: Solves the diamond problem by ensuring only one copy of the base class is
inherited.
class A { };
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };
Q47. Di erence between Public, Protected, and Private Inheritance
Public: Public → Public, Protected → Protected.
Protected: Public/Protected → Protected.
Private: All → Private.
Q48. Polymorphism in C++
Answer: Ability of functions/objects to take multiple forms.
Compile-time: Function & operator overloading.
Runtime: Virtual functions.
Q49. Virtual Functions
Answer: Functions declared in base class using virtual and overridden in derived
class for runtime polymorphism.
Q50. Pure Virtual Functions & Abstract Classes
Answer: A function with = 0 is a pure virtual function; a class with at least one pure
virtual function is abstract.
class Shape {
public:
virtual void draw() = 0; // pure virtual
};
Q51. Can constructors be virtual?
No, because object creation requires knowing the exact type.
Q52. Can destructors be virtual?
Yes, important to delete derived objects via base pointers.
Q53. Object Slicing
Occurs when a derived object is assigned to a base object, slicing o derived parts.
Q54. Aggregation vs Composition
Aggregation: Has-a relationship, object can exist independently.
Composition: Stronger relationship, object cannot exist without the container.
Q55. Overriding vs Overloading
Overriding: Same function signature in base & derived.
Overloading: Same name, di erent parameters in the same scope.
Q56. final Keyword in C++11
Prevents a class from being inherited or a virtual function from being overridden.
Q57. override Keyword
Explicitly marks a function as overriding a base class function.
Q58. Static Polymorphism
Achieved via templates & overloading — resolved at compile time.
Q59. Dynamic Polymorphism
Achieved via virtual functions — resolved at runtime.
Q60. Abstract Class vs Interface in C++
C++ has no direct interface keyword — abstract class with only pure virtual functions
works as interface.
Q61. Friend Function & Friend Class in OOP
Allow access to private/protected members from outside.
Q62. Encapsulation in C++
Binding data and methods into a single unit, controlling access.
Q63. Abstraction in C++
Hiding implementation details using abstract classes & interfaces.
Q64. Static Binding vs Dynamic Binding
Static: Function call resolved at compile time.
Dynamic: Resolved at runtime via virtual functions.
Q65. Virtual Table (vtable)
A lookup table used to resolve virtual function calls at runtime.
Q66. vptr in C++
Pointer to vtable maintained per object instance for dynamic dispatch.
Q67. Can we call virtual functions in constructors?
Yes, but only base class version will be called.
Q68. Covariant Return Type
Overridden function can return a more derived type than base function.
Q69. Multiple Dispatch in C++
C++ doesn’t directly support it, can be simulated using double dispatch.
Q70. Diamond Problem without Virtual Inheritance
Leads to two copies of base class data in derived object.
Q71. Run-Time Type Information (RTTI)
typeid and dynamic_cast allow type identification at runtime.
Q72. dynamic_cast in C++
Used for safe downcasting of pointers/references.
Q73. typeid Operator
Returns type information of an object.
Q74. Constructor Delegation in C++11
One constructor calls another in the same class.
Q75. Inheriting Constructors (C++11)
using Base::Base; allows derived to inherit base constructors.
Q76. Protected Constructors
Prevents direct instantiation but allows inheritance.
Q77. Non-virtual Interface (NVI) Idiom
Public non-virtual method calls a private virtual method.
Q78. CRTP (Curiously Recurring Template Pattern)
Base class template takes derived class as template parameter.
Q79. Multiple Inheritance Ambiguity Resolution
Use scope resolution A::func() to specify which base class function to call.
Q80. Pimpl Idiom
Pointer to implementation — hides implementation details to reduce compilation
dependencies.
Section 3 – Memory Management (Q81–Q110)
Q81. What is Memory Management in C++?
Answer: The process of allocating, using, and freeing memory e iciently to
prevent memory leaks and crashes.
C++ gives manual control (new, delete) and modern features like smart pointers.
Q82. Stack vs Heap Memory
Feature Stack Heap
Allocation Automatic Manual (new/malloc)
Size Limit Small Large
Speed Fast Slower
Lifetime Until function ends Until manually freed
Q83. new vs malloc
new → Calls constructor, type-safe, throws exception on failure.
malloc → Allocates raw memory, needs casting, returns NULL on failure.
int* p = new int(5);
delete p;
Q84. delete vs free
delete → Calls destructor, used with new.
free → Used with malloc, does not call destructor.
Q85. Dangling Pointer
A pointer pointing to freed memory.
Solution → Set pointer to nullptr after delete.
Q86. Memory Leak
Occurs when allocated memory is never freed.
Solution → Always delete allocated memory or use smart pointers.
Q87. Smart Pointers in C++
Answer: Objects that manage memory automatically.
Types:
unique_ptr → Exclusive ownership.
shared_ptr → Shared ownership.
weak_ptr → Non-owning reference.
Q88. unique_ptr Example
#include <memory>
auto ptr = std::make_unique<int>(10);
Q89. shared_ptr Example
#include <memory>
auto ptr1 = std::make_shared<int>(10);
auto ptr2 = ptr1; // shared ownership
Q90. weak_ptr Example
Used to break cyclic references in shared_ptr.
Q91. RAII (Resource Acquisition Is Initialization)
Answer: Ties resource lifetime to object lifetime to prevent leaks.
Q92. Placement new
Constructs object in pre-allocated memory.
char bu er[sizeof(int)];
int* p = new (bu er) int(42);
Q93. Shallow Copy vs Deep Copy (Memory)
Shallow → Copies pointer only.
Deep → Copies actual memory content.
Q94. Memory Alignment in C++
Ensures variables are stored at memory addresses optimal for CPU access.
Q95. memset() and memcpy()
memset → Fills memory with a value.
memcpy → Copies memory block.
Q96. Memory Pooling
Reuses a pool of memory blocks for frequent allocations.
Q97. Garbage Collection in C++
No built-in GC — manual or smart pointers used.
Q98. Bu er Overflow
Occurs when writing outside allocated memory → can cause security risks.
Q99. Segmentation Fault
Accessing invalid memory location.
Q100. Stack Overflow
When stack memory limit exceeded (e.g., deep recursion).
Q101. Memory Fragmentation
Unused small memory blocks scattered — reduces allocation e iciency.
Q102. Object Lifetime
Time between object creation and destruction.
Q103. Heap Corruption
Invalid memory writes cause heap metadata damage.
Q104. Static Memory Allocation
Done at compile time (global & static variables).
Q105. Dynamic Memory Allocation
Done at runtime (new, malloc).
Q106. Allocators in C++ STL
Manage container memory (e.g., std::allocator).
Q107. Overloading new & delete Operators
Custom memory allocation logic.
Q108. Preventing Memory Leaks
Use RAII, smart pointers, and avoid raw new/delete.
Q109. Page Fault in Memory
Occurs when data not in RAM is accessed.
Q110. Valgrind Tool
Used to detect memory leaks & invalid memory usage.
Section 4 – STL (Q111–Q140)
Q111. What is the STL in C++?
Answer:
The Standard Template Library is a collection of generic, reusable classes and
functions for data structures and algorithms.
Main components:
1. Containers (store data)
2. Iterators (access data)
3. Algorithms (process data)
Q112. Types of STL Containers
1. Sequence Containers → vector, deque, list, array, forward_list.
2. Associative Containers → set, multiset, map, multimap.
3. Unordered Containers → unordered_set, unordered_map.
4. Container Adapters → stack, queue, priority_queue.
Q113. vector in STL
Dynamic array with automatic resizing.
#include <vector>
vector<int> v = {1, 2, 3};
v.push_back(4);
Q114. list in STL
Doubly linked list.
#include <list>
list<int> l = {1, 2, 3};
l.push_front(0);
Q115. deque in STL
Double-ended queue allowing insertion/removal from both ends.
Q116. forward_list in STL
Singly linked list (less memory overhead).
Q117. array in STL
Fixed-size array wrapper.
#include <array>
array<int, 3> arr = {1, 2, 3};
Q118. set in STL
Stores unique elements in sorted order.
#include <set>
set<int> s = {3, 1, 2};
Q119. multiset in STL
Stores elements in sorted order but allows duplicates.
Q120. unordered_set in STL
Stores unique elements with hashing (faster lookups).
Q121. map in STL
Key-value pairs in sorted order by key.
#include <map>
map<int, string> m;
m[1] = "One";
Q122. multimap in STL
Key-value pairs allowing duplicate keys.
Q123. unordered_map in STL
Key-value pairs using hash table for average O(1) lookups.
Q124. stack in STL
LIFO structure.
#include <stack>
stack<int> st;
st.push(1);
Q125. queue in STL
FIFO structure.
Q126. priority_queue in STL
Heap-based container (max-heap by default).
Q127. Iterators in STL
Answer: Objects that point to elements in containers.
Types:
Input Iterator
Output Iterator
Forward Iterator
Bidirectional Iterator
Random Access Iterator
Q128. begin() and end() in STL
begin() → points to first element.
end() → points one past the last element.
Q129. reverse_iterator in STL
Used to iterate in reverse order.
Q130. const_iterator in STL
Iterator that cannot modify elements.
Q131. Algorithms in STL
Common ones: sort, reverse, count, find, accumulate.
Q132. sort() in STL
#include <algorithm>
sort(v.begin(), v.end());
Q133. reverse() in STL
reverse(v.begin(), v.end());
Q134. find() in STL
auto it = find(v.begin(), v.end(), 3);
Q135. count() in STL
Counts occurrences of a value.
Q136. accumulate() in STL
Sum of elements.
#include <numeric>
int sum = accumulate(v.begin(), v.end(), 0);
Q137. lower_bound() & upper_bound()
lower_bound → first element ≥ value.
upper_bound → first element > value.
Q138. erase() in STL
Removes elements from a container.
Q139. remove() vs erase() in STL
remove → shifts elements, does not change container size.
erase → changes container size.
Q140. emplace() vs insert() in STL
emplace → constructs element in place (faster).
insert → copies/moves element into container.
Section 5 – Advanced Topics (Q141–Q170)
Q141. What are the major features introduced in C++11?
Answer:
auto type deduction
nullptr keyword
Range-based for loops
Lambda functions
Smart pointers (unique_ptr, shared_ptr)
Move semantics & rvalue references
Uniform initialization {}
Q142. What is Move Semantics in C++11?
Answer: Transfers ownership of resources instead of copying, improving
performance.
string a = "Hello";
string b = move(a); // avoids deep copy
Q143. What is an Rvalue Reference (&&)?
Answer: Reference to a temporary object, used in move semantics.
Q144. What is std::thread in C++11?
Answer: Allows creation of lightweight threads for parallel execution.
#include <thread>
void func() {}
thread t(func);
t.join();
Q145. Mutex in C++11
Answer: Used to protect shared resources from race conditions.
Q146. std::lock_guard and std::unique_lock
RAII wrappers for mutexes — ensure unlocking even if exceptions occur.
Q147. Future and Promise in C++11
Answer: Mechanisms for asynchronous communication between threads.
Q148. What is std::async?
Runs a function asynchronously, returning a future.
Q149. Condition Variables
Used for thread synchronization — one thread waits until another signals.
Q150. Atomic Operations
Answer: Lock-free operations on variables (e.g., std::atomic<int>).
Q151. constexpr in C++11
Compile-time constant expressions.
Q152. noexcept Keyword
Indicates a function does not throw exceptions.
Q153. override and final in Modern C++
override → Ensures function overrides a base virtual function.
final → Prevents further overriding or inheritance.
Q154. What is a Variadic Template?
Templates that take variable number of arguments.
Q155. Fold Expressions in C++17
Simplifies variadic template expansion.
template<typename... Args>
auto sum(Args... args) { return (args + ...); }
Q156. Structured Bindings in C++17
auto [a, b] = pair<int,int>(1,2);
Q157. What is std::optional in C++17?
Holds a value or no value (avoids null pointers).
Q158. What is std::variant in C++17?
Type-safe union that can hold one of multiple types.
Q159. std::any in C++17
Holds any type in a type-erased manner.
Q160. What is if constexpr in C++17?
Compile-time conditional branching.
Q161. Concepts in C++20
Defines constraints for template parameters.
Q162. Ranges in C++20
Provides a more functional way to work with collections.
Q163. Coroutines in C++20
Allows writing asynchronous code with co_await, co_yield.
Q164. Design Pattern – Singleton
Ensures a class has only one instance.
Q165. Design Pattern – Factory Method
Creates objects without specifying the exact class.
Q166. Design Pattern – Observer
One-to-many dependency between objects.
Q167. SFINAE (Substitution Failure Is Not An Error)
Technique for template metaprogramming.
Q168. What is Memory Order in Atomics?
Specifies how memory operations are ordered in multithreading.
Q169. Inline Namespace
Versioning mechanism for namespaces.
Q170. What is std::filesystem in C++17?
Provides tools for file and directory manipulation.
Section 6 – Coding Problems (Q171–Q200)
Q171. Reverse a String
string s = "Tokyo";
reverse(s.begin(), s.end()); // "oykoT"
Q172. Check Palindrome String
bool isPal(string s) {
string r = s;
reverse(r.begin(), r.end());
return s == r;
Q173. Find Factorial (Recursion)
int fact(int n) {
return (n<=1) ? 1 : n * fact(n-1);
Q174. Fibonacci Sequence (Recursion)
int fib(int n) {
return (n<=1) ? n : fib(n-1) + fib(n-2);
Q175. Find Largest Element in Array
int mx = *max_element(arr, arr+n);
Q176. Count Vowels in a String
int countV(string s) {
int c=0; string v="aeiouAEIOU";
for(char ch:s) if(v.find(ch)!=string::npos) c++;
return c;
Q177. Reverse an Integer
int revNum(int n) {
int r=0;
while(n){ r = r*10 + n%10; n/=10; }
return r;
Q178. Check Prime Number
bool prime(int n) {
if(n<2) return false;
for(int i=2;i*i<=n;i++) if(n%i==0) return false;
return true;
Q179. Binary Search
int bs(vector<int>&a,int t){
int l=0,r=a.size()-1;
while(l<=r){
int m=l+(r-l)/2;
if(a[m]==t) return m;
if(a[m]<t) l=m+1; else r=m-1;
return -1;
Q180. Linear Search
for(int i=0;i<n;i++) if(arr[i]==x) return i;
Q181. Remove Duplicates from Vector
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
Q182. Sort a Vector in Descending Order
sort(v.rbegin(), v.rend());
Q183. Find GCD of Two Numbers
int gcd(int a,int b){ return b==0?a:gcd(b,a%b); }
Q184. Find LCM of Two Numbers
int lcm(int a,int b){ return a/gcd(a,b)*b; }
Q185. Swap Two Numbers without Temp Variable
a ^= b; b ^= a; a ^= b;
Q186. Find Second Largest Element
sort(v.begin(), v.end());
int second = v[v.size()-2];
Q187. Count Occurrences of Element
int c = count(v.begin(), v.end(), x);
Q188. Merge Two Sorted Arrays
merge(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
Q189. Matrix Transpose
for(int i=0;i<n;i++)
for(int j=i;j<m;j++)
swap(mat[i][j],mat[j][i]);
Q190. Sum of Digits of Number
int sum=0; while(n){ sum+=n%10; n/=10; }
Q191. Armstrong Number
bool arm(int n){
int t=n,s=0,d=to_string(n).size();
while(t){ s+=pow(t%10,d); t/=10; }
return s==n;
Q192. Reverse Words in a String
stringstream ss(s);
string w,res;
while(ss>>w) res = w + " " + res;
Q193. Check Anagram
sort(a.begin(),a.end());
sort(b.begin(),b.end());
return a==b;
Q194. Find Missing Number (1 to n)
int sum = n*(n+1)/2;
for(int x:arr) sum -= x;
Q195. Kadane’s Algorithm (Max Subarray Sum)
int best=arr[0],sum=0;
for(int x:arr){
sum=max(x,sum+x);
best=max(best,sum);
Q196. Count Words in a String
int c = distance(istream_iterator<string>(ss), {});
Q197. Remove Spaces from String
s.erase(remove(s.begin(), s.end(), ' '), s.end());
Q198. Find Intersection of Two Arrays
set_intersection(a.begin(),a.end(),b.begin(),b.end(),back_inserter(res));
Q199. Check Balanced Parentheses
stack<char> st;
for(char ch:s){
if(ch=='(') st.push(ch);
else if(ch==')'){ if(st.empty()) return false; st.pop(); }
return st.empty();
Q200. Implement Stack using STL
stack<int> s;
s.push(10);
s.pop();