Installation & Setup
Before writing code, you need to set up your computer. Pick your operating system below and follow the steps in order.
- 1
Install Visual Studio CodeThe code editor where you'll write your programs.
- 2
Install Xcode Command Line ToolsThis gives you the C++ compiler on Mac.xcode-select --install
- 3
Install the C/C++ Extension in VS CodeSearch "C/C++" in the Extensions tab and install it.
- 4
Verify the compiler is installedRun this in the terminal — a version number means success.clang++ --version
- 5
Create, compile, and run your first programYou're ready to write code! (See section 3.)
- 1
Install Visual Studio CodeThe code editor where you'll write your programs.
- 2
Install MSYS2A tool that lets you install the compiler on Windows.
- 3
Install the GCC CompilerInstalled through MSYS2 — this compiles your C++ code.
- 4
Add GCC to the System PATHSo your computer can find the compiler from anywhere.
- 5
Install the C/C++ Extension in VS CodeSearch "C/C++" in the Extensions tab and install it.
- 6
Verify the compiler is installedRun this in the terminal — a version number means success.g++ --version
- 7
Create, compile, and run your first programYou're ready to write code! (See section 3.)
Boiler Plate
Every C++ program starts with the same basic code. This starter code is called boilerplate.
#include <iostream>
using namespace std;
int main() {
// write your code here
return 0;
}
#include <iostream>
Brings in input/output features
using namespace std;
Lets you write cout, not std::cout
int main() { }
Where the program starts running
return 0;
Tells the system it ran successfully
Key points
- Every program must have a main() function.
- Your code goes inside the curly braces { }.
- Each statement ends with a semicolon ;
Write Your First Program
Let's make the program actually do something — print a message on the screen.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
What each part does
- cout prints text on the screen.
- Text goes inside double quotes " ".
- << sends the text into cout.
Variables & Data Types
Before writing real logic, you need to know how C++ stores and labels data.
Comments
// single-line comment
/* multi-line
comment */
- Single-line: //
- Multi-line: /* ... */
- Used to explain code — never affects the output.
Syntax
- Every statement ends with a semicolon ;
- Code blocks are wrapped in { }
- C++ is case-sensitive —
Ageandageare different.
Word vs Keyword
| Basis | Word | Keyword |
|---|---|---|
| Meaning | Any name you choose | A reserved word in C++ |
| Can rename? | Yes | No |
| Example | age, total | int, return, if |
Variables
int age = 20;
- Must be declared with a data type before use.
- Its value can change later in the program.
- Every variable needs a unique name.
Naming Convention, Identifiers & Literals
Naming rules
- Can contain letters, digits, and underscore _
- Cannot start with a digit.
- Cannot use a keyword as a name.
- No spaces allowed.
| Literal Type | Example |
|---|---|
| Integer | 10, -5 |
| Floating-point | 3.14 |
| Character | 'A' |
| String | "Hello" |
| Boolean | true, false |
A literal is a fixed value written directly in code.
Constants
const int maxScore = 100;
Data Types
| Type | Stores | Example |
|---|---|---|
| int | Whole numbers | 10, -3 |
| float | Decimal numbers | 3.14 |
| double | Larger decimal numbers | 3.14159265 |
| char | A single character | 'A' |
| bool | true / false | true |
| void | No value at all | used for functions |
Garbage Value
- Happens when you skip giving a variable a starting value.
- The value is leftover data from memory — not zero, not predictable.
- Always initialize variables to avoid this.
sizeof Operator
sizeof operator returns the memory size (in bytes) that a data type or variable occupies.cout << sizeof(int);
Type Conversion
Sometimes C++ needs to convert one data type into another. This can happen automatically or manually.
Implicit Conversion
int a = 5;
double b = a; // int auto-converted to double
Explicit Conversion
double x = 9.7;
int y = (int)x; // manually converted
Type Casting
- C-style:
(int)x - C++-style:
static_cast<int>(x)
| Basis | Implicit | Explicit |
|---|---|---|
| Done by | Compiler | Programmer |
| Control | Automatic | Manual |
| Risk | May lose data silently | Intentional, controlled |
Operators
Operators let you perform actions on variables and values — math, comparisons, and logic.
Unary vs Binary
| Basis | Unary | Binary |
|---|---|---|
| Operands needed | 1 | 2 |
| Example | -a, ++a | a + b |
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
Relational Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Assignment Operators
| Operator | Meaning | Same as |
|---|---|---|
= | Assign | — |
+= | Add and assign | a = a + b |
-= | Subtract and assign | a = a - b |
*= | Multiply and assign | a = a * b |
/= | Divide and assign | a = a / b |
%= | Modulus and assign | a = a % b |
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
&& | AND — true if both are true | a && b |
|| | OR — true if either is true | a || b |
! | NOT — reverses the result | !a |
Input & Output
How your program talks to the user — taking input and printing output.
cin
cin is used to take input from the user through the keyboard.int age;
cin >> age;
cout
cout is used to print output to the screen.cout << "Age: " << age;
getline() & cin.ignore()
getline() reads an entire line of text, including spaces — something cin alone cannot do.string fullName;
getline(cin, fullName);
Reading a String After an Int
cin and then a full line with getline(), the leftover newline from the number is picked up by getline() — so it reads an empty line instead of the real input.cin.ignore() between them to throw away that leftover newline.int age;
string name;
cin >> age; // leftover '\n' stays in the input buffer
cin.ignore(); // throw away that leftover newline
getline(cin, name); // now reads the whole line correctly
cin.ignore() and name comes out empty — a classic beginner bug.endl vs \n
| Basis | endl | \n |
|---|---|---|
| What it does | New line + flushes buffer | Just a new line |
| Speed | Slower | Faster |
| Usage | cout << endl; | cout << "\n"; |
Escape Sequences
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab space |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
Decision Making | Conditional Statements
Conditional statements let your program make choices and run different code based on conditions.
if
if statement runs a block of code only when a condition is true.if (age >= 18) {
cout << "Adult";
}
if else
if-else statement runs one block if the condition is true, and a different block if it's false.if (age >= 18) {
cout << "Adult";
} else {
cout << "Minor";
}
Nested if
if statement placed inside another if statement.if (age >= 18) {
if (hasID) {
cout << "Entry allowed";
}
}
else if Ladder
if (marks >= 90) {
cout << "Grade A";
} else if (marks >= 75) {
cout << "Grade B";
} else {
cout << "Grade C";
}
switch case
switch statement compares one variable against several fixed values, running the matching case.switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
default: cout << "Invalid";
}
- Every
caseshould end with a break, or execution "falls through" to the next case. defaultruns when no case matches.
Ternary Operator
string result = (age >= 18) ? "Adult" : "Minor";
Syntax: condition ? valueIfTrue : valueIfFalse
if vs switch
| Basis | if-else Ladder | switch |
|---|---|---|
| Condition type | Ranges & complex conditions | Exact value matches |
| Readability | Harder with many checks | Cleaner for many fixed values |
| Speed | Checks sequentially | Often faster (jump table) |
Loops
Loops let you repeat a block of code multiple times without writing it again and again.
Why Loops?
- Avoids repeating the same code manually.
- Automates repetitive tasks — printing, counting, calculating.
- Makes programs shorter and easier to maintain.
Types of Loops
| Loop | Best Used When |
|---|---|
| for | Number of iterations is known |
| while | Number of iterations is unknown |
| do-while | Code must run at least once |
for Loop
for loop repeats a block of code a specific number of times.for (int i = 0; i < 5; i++) {
cout << i;
}
- Syntax:
for(start; stop; step){ } - A missing stop condition creates an infinite for loop.
while Loop
while loop repeats a block of code as long as its condition stays true.int i = 0;
while (i < 5) {
cout << i;
i++;
}
- Syntax:
while(condition){ } - A condition that never becomes false creates an infinite while loop.
do while Loop
do-while loop runs the code block first, then checks the condition — guaranteeing at least one run.int i = 0;
do {
cout << i;
i++;
} while (i < 5);
- Syntax:
do{ statement }while(condition); - Executes at least once, even if the condition is false.
- Don't forget the semicolon after
while(condition).
Jump Statements
Jump statements let you control the flow inside a loop directly.
break
break statement immediately exits the loop or switch it's inside.for (int i = 0; i < 10; i++) {
if (i == 5) break;
cout << i;
}
continue
continue statement skips the current iteration and moves to the next one.for (int i = 0; i < 5; i++) {
if (i == 2) continue;
cout << i;
}
| Basis | break | continue |
|---|---|---|
| Effect | Exits the loop completely | Skips only the current iteration |
| Loop continues after? | No | Yes |
Nested Loops
A loop can be placed inside another loop — this is how patterns and grids are built.
Loop Inside Loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << "* ";
}
cout << "\n";
}
Pattern Programming
- The outer loop usually controls the number of rows.
- The inner loop usually controls what's printed in each row.
- Used to build shapes like squares, triangles, and pyramids.
Function Basics
Functions let you organize code into reusable blocks instead of repeating it everywhere.
What is a Function?
- Avoids writing the same code repeatedly.
- Keeps programs organized and easier to read.
- Can be called any number of times.
Function Declaration
int add(int a, int b);
Also called a function prototype.
Function Definition
int add(int a, int b) {
return a + b;
}
Function Calling
int result = add(5, 3);
Return Type
int,double,string— the function returns a value of that type.void— the function returns nothing.- Use the return keyword to send the value back.
Function Features
How arguments are passed to a function changes what happens to the original variables.
Call by Value
void update(int x) {
x = 100; // original stays unchanged
}
Call by Reference
void update(int& x) {
x = 100; // original changes too
}
| Basis | Call by Value | Call by Reference |
|---|---|---|
| What's passed | A copy of the variable | The variable itself |
| Original affected? | No | Yes |
| Syntax | int x | int& x |
Default Arguments
void greet(string name = "Guest") {
cout << "Hello " << name;
}
- Default arguments must be assigned from right to left.
- Once one parameter has a default value, every parameter after it must too.
One-Dimensional Arrays
Arrays let you store many values of the same type under a single name.
Need of a Data Structure
- Storing 100 values as 100 separate variables is unmanageable.
- Data structures group related data together.
- Different problems need different structures.
Types of Data Structures
| Structure | What It Does |
|---|---|
| Array | Stores same-type elements in contiguous memory |
| String | A sequence of characters |
| Linked List | Elements connected using pointers |
| Queue | First-In, First-Out (FIFO) |
| Stack | Last-In, First-Out (LIFO) |
| Tree | Hierarchical, branching structure |
| Graph | Nodes connected by edges |
Array Initialisation
int arr[5] = {1, 2, 3, 4, 5};
Array Traversal / Iteration
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
Garbage Values
- An uninitialized array element holds a garbage value, just like a regular variable.
- Always initialize arrays before reading from them.
sizeof Operator
sizeof(arr) returns the total bytes it occupies — not the number of elements.int count = sizeof(arr) / sizeof(arr[0]);
Dividing total size by one element's size gives the number of elements.
Array–Pointer Relation
arr and &arr[0] point to the same place.arr[i]is the same as*(arr + i)- The array name itself cannot be reassigned to point elsewhere.
Undefined Behavior
- Accessing an index outside the array's valid range causes undefined behavior.
- The result is unpredictable — it may print garbage, crash, or seem to "work" incorrectly.
Default Values
- Global / static arrays are automatically set to 0.
- Local arrays are not automatically initialized — they hold garbage values.
Enhanced for Loop
for (int x : arr) {
cout << x;
}
Two-Dimensional Arrays
A 2D array stores data in rows and columns — like a table or a grid.
What is a 2D Array?
Declaration & Initialization
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
First bracket = number of rows, second bracket = number of columns.
Input & Output
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
cin >> matrix[i][j];
Memory Representation
Passing 2D Arrays to Functions
void printMatrix(int arr[][3], int rows) {
// rows known, columns fixed at 3
}
C-Style Strings
Before the string class, C++ inherited strings from C — plain character arrays.
Character Array
'\0'.char name[] = "Hi"; // stored as 'H','i','\0'
Input using cin
cin >> name;reads a C-string.- It stops reading at the first space.
Input using cin.getline(name, size)
cin.getline() reads a full line into a character array, including spaces, up to a given size limit.cin.getline(name, 50);
String Functions
| Function | What It Does |
|---|---|
strlen(str) | Returns the length of the string |
strcpy(dest, src) | Copies one string into another |
strcat(str1, str2) | Joins two strings together |
strcmp(str1, str2) | Compares two strings — returns 0 if equal |
Problems with C Strings
- Fixed size — cannot grow automatically.
- Needs manual memory handling.
- Easy to accidentally overflow the buffer.
- No built-in safety checks.
String Class
The string class makes working with text far easier and safer than character arrays.
string Library
string class provides a modern, flexible way to store and manipulate text in C++.#include <string>
Input using cin
string name;
cin >> name; // still stops at a space
Input using getline
getline(cin, name); // reads the full line
String Traversal
for (char c : name) {
cout << c;
}
length() / size()
- Both return the number of characters in the string.
- They do exactly the same thing — use whichever you prefer.
Concatenation (+)
string full = first + " " + last;
Comparison
==, !=, <, > — comparison follows dictionary order.Memory Representation
string class manages its own memory — it automatically grows and shrinks as needed, unlike a fixed-size character array.Common Methods
| Method | What It Does |
|---|---|
.length() | Returns the number of characters |
.append(str) | Adds text to the end |
.push_back(c) | Adds one character to the end |
.pop_back() | Removes the last character |
.insert(i, str) | Inserts text at a given position |
.erase(pos, count) | Removes characters starting at a position |
.substr(start, len) | Extracts part of the string |
.find(sub) | Finds the position of a substring |
.replace(start, count, str) | Replaces part of the string |
.compare(str) | Compares two strings |
.swap(str) | Swaps contents with another string |
char[] vs string
| Basis | char[] | string |
|---|---|---|
| Type | C-style string | C++ string class |
| Size | Fixed | Dynamic |
| End marker | Uses \0 | Managed automatically |
| Operations | Difficult | Easy |
| Speed | Faster | More convenient |
Pointer Basics
A pointer gives you direct access to where data actually lives in memory.
Why Pointers?
- Allow direct access to memory addresses.
- Enable dynamic memory allocation.
- Let functions modify the original variable (call by reference).
- Essential for arrays, strings, and data structures.
Memory Address
Address Of Operator (&)
& operator returns the memory address of a variable.cout << #
Pointer Variables
Pointer Declaration & Initialization
int num = 10;
int* ptr = #
Dereferencing Operator (*)
* operator accesses the value stored at the address a pointer points to.cout << *ptr; // prints 10
Pointer Memory Representation
Pointer Operations
Pointers support their own set of operations, separate from normal variables.
Pointer Arithmetic
| Operation | Effect |
|---|---|
ptr++ | Moves to the next element |
ptr-- | Moves to the previous element |
ptr + n | Moves forward by n elements |
ptr - n | Moves backward by n elements |
Comparing Pointers
==, !=, <, > — useful for checking if they point to the same location.Size of Pointer
sizeof(ptr) returns the size of the pointer itself (commonly 8 bytes on 64-bit systems) — not the size of the data it points to.Pointers and Functions
Pointers let functions reach outside their own scope and modify the caller's variables.
Call By Reference using Pointers
void update(int* ptr) {
*ptr = 100;
}
Returning Pointers from Functions
- Never return the address of a local variable — it's destroyed once the function ends.
- Safe to return addresses of static or dynamically allocated variables.
Return Multiple Values from Function
Pointers and Arrays
Arrays and pointers are closely linked in C++ — an array name is essentially a pointer.
Array Name as Base Address
arr is the same as &arr[0].Accessing Array Elements using Pointers
cout << *(arr + i); // same as arr[i]
Array Traversal using Pointers
for (int* p = arr; p < arr + 5; p++) {
cout << *p;
}
Relationship Between Arrays and Pointers
arr[i]and*(arr + i)mean the same thing.- The array name is a constant pointer — it cannot be reassigned to point elsewhere.
Advanced Pointers
A few special pointer types cover cases beyond a standard pointer.
Null Pointer
int* ptr = nullptr;
Void Pointer
void* ptr;
Double Pointer
int** ptr2 = &ptr;
Dynamic Memory Allocation
C++ lets you request and release memory manually, while the program is running.
new Operator
new operator allocates memory on the heap while the program is running.int* ptr = new int(10);
delete Operator
delete operator frees memory that was allocated with new, returning it to the system.delete ptr;
Dynamic Arrays
new[], letting the size be decided while the program runs.int* arr = new int[5];
delete[] arr;
Arrays created with new[] must be freed with delete[], not plain delete.
Memory Leaks
delete.- Every
newshould be paired with a matchingdelete. - Every
new[]should be paired withdelete[]. - Leaks build up over time and can slow down or crash long-running programs.
Heap vs Stack
| Basis | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Manual (new / delete) |
| Speed | Faster | Slower |
| Size | Limited | Large |
| Lifetime | Ends when scope ends | Until explicitly deleted |
| Managed by | Compiler | Programmer |
Structures
A structure lets you group related variables of different types under a single name.
Why Structure?
- Groups different types of variables under one name.
- Makes related data easier to manage and pass around together.
Structure (struct)
struct Student {
string name;
int age;
};
Creating Structures
Student s1;
s1.name = "Raj";
s1.age = 20;
Arrays of Structures
Student students[3];
Union
A union looks similar to a structure, but works very differently in memory.
Union
union Data {
int i;
float f;
};
Difference between Struct and Union
| Basis | Struct | Union |
|---|---|---|
| Memory | Separate for each member | Shared among all members |
| Size | Sum of all members | Size of the largest member |
| Access | All members usable at once | Only one member valid at a time |
Enumerations
Enums give meaningful names to a fixed set of integer constants.
enum
enum Day { MON, TUE, WED };
Default values start from 0 and increase by 1 unless specified otherwise.
enum class
enum class is a scoped, type-safe version of enum introduced in modern C++.enum class Day { MON, TUE, WED };
enum vs enum class
| Basis | enum | enum class |
|---|---|---|
| Style | C style | Modern C++ |
| Scope | Global | Scoped |
| Type safety | Not type safe | Type safe |
| int conversion | Implicit | No implicit conversion |
| Access | MON | Day::MON |
typedef & using Alias
Both give an existing data type a new, more convenient name.
typedef
typedef is used to create another name (alias) for an existing data type.typedef unsigned long ulong;
using Alias
using keyword also creates a type alias — it is the modern replacement for typedef.using ulong = unsigned long;
OOPS Introduction
Object-Oriented Programming is a completely different way of thinking about code — built around objects instead of just functions.
Why OOP?
- Models real-world entities as objects in code.
- Makes large programs easier to organize and manage.
- Encourages reusable, secure, well-structured code.
What is a Programming Paradigm?
Types of Programming
| Paradigm | Approach |
|---|---|
| Imperative (Procedural) | Step-by-step instructions, organized into functions |
| Functional | Code built from pure functions, avoiding shared state |
| Object-Oriented | Code organized around objects that hold data and behavior |
Problems with Procedural Programming
- Data and functions are separate — data isn't well protected.
- Hard to manage as the codebase grows large.
- Difficult to reuse code across different parts of a project.
Special About OOP
Features of OOP
| Feature | What It Means |
|---|---|
| Class & Object | The blueprint, and the real thing built from it |
| Encapsulation | Bundling data and functions together, hiding details |
| Abstraction | Showing only essential features, hiding complexity |
| Inheritance | Reusing properties from an existing class |
| Polymorphism | One action, many forms |
Class
A class is where OOP begins — the blueprint every object is built from.
What is a Class?
Creating a Class
class Car {
public:
string brand;
void honk() { cout << "Beep!"; }
};
Data Members
brand for a Car.Member Functions
honk() for a Car.Object
An object is the real, usable thing built from a class's blueprint.
Instance of a Class
Creating Objects
| Type | Where It Lives | Example |
|---|---|---|
| Static Object | Stack | Car c1; |
| Dynamic Object | Heap (using new) | Car* c2 = new Car(); |
Memory Representation of Objects
Object vs Class
| Basis | Class | Object |
|---|---|---|
| What it is | Blueprint | The actual building |
| Memory | No memory allocated | Takes up memory |
| Count | One class | Many objects possible |
Access Modifiers
Access modifiers control who is allowed to see or use a class's members.
| Modifier | Accessible From |
|---|---|
| public | Anywhere — global level |
| private | Only inside the same class |
| protected | Inside the class and its derived classes |
Constructors
A constructor is a special function that sets up an object the moment it's created.
What is a Constructor?
- Name must be exactly the same as the class name.
- Has no return type — not even
void. - Called automatically — never invoked manually.
- Cannot be static, virtual, or inherited.
Default Constructor
class Car {
public:
Car() { cout << "Car created"; }
};
Parameterised Constructor
Car(string b) { brand = b; }
this Keyword
this is a pointer that refers to the current object calling the function.Car(string brand) {
this->brand = brand; // distinguishes member from parameter
}
Copy Constructor
Car c2 = c1; // copy constructor called
Shallow Copy vs Deep Copy
| Basis | Shallow Copy | Deep Copy |
|---|---|---|
| What's copied | Only the pointer/reference | The actual data being pointed to |
| Shared memory? | Yes — risky | No — fully independent |
Constructor Overloading
Member Function Outside the Class
void Car::honk() {
cout << "Beep!";
}
Syntax: returnType className::methodName — the method must still be declared inside the class first.
Initialisation List
Car(string b) : brand(b) { }
Destructor
A destructor is the counterpart to a constructor — it cleans up an object right before it's destroyed.
Object Life Cycle
Destructor Syntax
~Car() { cout << "Car destroyed"; }
- Same name as the class, prefixed with
~ - Takes no parameters and returns nothing.
- Only one destructor is allowed per class — it cannot be overloaded.
Encapsulation
Encapsulation wraps data and the functions that use it into one protected unit.
The Problem
Getter & Setter
int getAge() { return age; }
void setAge(int a) { age = a; }
Data Hiding
private keyword.Encapsulation
Encapsulation vs Data Hiding
| Basis | Encapsulation | Data Hiding |
|---|---|---|
| What it does | Bundles data + functions together | Restricts access to that data |
| Scope | Broader concept | A part of encapsulation |
Benefits
Static Members
Static members belong to the class itself, not to any single object.
Why Static?
- Avoids duplicating the same data for every object.
- Shares common data across all objects.
- Belongs to the class, not an individual object.
Static Variables
static int count; // declaration
int Car::count = 0; // initialisation, outside the class
- Initialised outside the class.
- Can be accessed using the class name directly.
Static Function
- Invoked using the class name.
- Can access only other static members.
- Cannot use the
thispointer.
Inheritance Basics
Inheritance lets one class reuse the properties and functions of another.
Why Inheritance?
- Reuses existing code instead of writing it again.
- Reduces code duplication.
- Makes code easier to maintain.
Parent (Base) Class
Child (Derived) Class
Syntax
class ChildClass : accessModifier ParentClass
{
// Child Class
};
Types of Inheritance
C++ supports five different patterns for how classes can inherit from one another.
Single Inheritance
A │ B
Multilevel Inheritance
A │ B │ C
Hierarchical Inheritance
A
/ \
B CMultiple Inheritance
A B
\ /
C- If both parent classes have a member with the same name, ambiguity occurs.
- Resolved using the Scope Resolution Operator (::) — e.g.
obj.A::display();
Hybrid Inheritance
A
/ \
B C
\ /
DDiamond Problem
A specific ambiguity issue that appears in hybrid inheritance.
Solutions
| Solution | What It Does |
|---|---|
| Scope Resolution (::) | Specifies exactly which parent's member to use |
| Virtual Inheritance | Ensures only one shared copy of the base class is inherited |
Constructor & Destructor Calling Order
In inheritance, constructors and destructors run in a strict, predictable order.
Constructor Order
Destructor Order
Destruction always happens in the reverse order of construction.
Access Mode Summary
The inheritance type you choose changes how a parent's members are accessed in the child class.
| Parent Member | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|
| Public | Public | Protected | Private |
| Protected | Protected | Protected | Private |
| Private | Not Accessible | Not Accessible | Not Accessible |
Polymorphism
Polymorphism means "many forms" — the same action behaving differently depending on the context.
Types of Polymorphism
| Type | Resolved | Also Known As |
|---|---|---|
| Compile-Time | At compile time | Static / Early Binding |
| Run-Time | At run time | Dynamic / Late Binding |
Binding means connecting a function call with its actual function implementation.
Compile-Time Polymorphism
Achieved through function, constructor, or operator overloading.
Function Overloading
- Function name must stay the same.
- Parameters must differ — in number, type, or order.
- Return type alone cannot overload a function.
Operator Overloading
+ or == new tricks for your own classes.returnType operator operatorSymbol(parameters);
- Only existing operators can be overloaded — new ones cannot be created.
- At least one operand must be a user-defined type.
::,.,?:, andsizeofcannot be overloaded.
Run-Time Polymorphism
Achieved through function overriding and virtual functions.
Function Overriding
- Requires both a parent and a child class.
- Function name and parameters must match exactly.
- Achieved through inheritance.
Virtual Function
virtual void speak();
- Declared with the
virtualkeyword in the base class. - Must be overridden in the derived class.
- Works through a base class pointer or reference.
- Constructors cannot be virtual.
- Static member functions cannot be virtual.
| Basis | Static Binding | Dynamic Binding |
|---|---|---|
| Decision based on | Pointer / reference type | The actual object being pointed to |
| Also called | Early binding | Late binding |
The override keyword is optional, but makes overriding intent explicit.
Abstraction
Abstraction is about showing only what matters, and hiding the messy details.
| Type | Meaning |
|---|---|
| Partial Abstraction | Some details hidden, some visible |
| Complete Abstraction | All implementation details hidden |
Partial Abstraction
Achieved using regular classes with private members.
Abstract Class
A class specifically designed to be incomplete, forcing derived classes to finish it.
- Contains at least one pure virtual function.
- Cannot create objects of an abstract class directly.
- Can still have constructors.
- Can contain normal member functions and data members.
Pure Virtual Function
The function that makes a class abstract in the first place.
virtual returnType functionName(parameters) = 0;
- Declared using
= 0. - Must be overridden in the derived class.
- If not overridden, the child class also becomes abstract.
Interface in C++
C++ doesn't have a dedicated "interface" keyword — it's simulated using abstract classes.
- Contains only pure virtual functions.
- Cannot create objects from it.
- Defines a strict contract for derived classes.
- Supports implementing multiple interfaces.
Abstraction vs Encapsulation
| Basis | Abstraction | Encapsulation |
|---|---|---|
| Focus | Hiding complexity | Hiding data |
| Achieved via | Abstract classes, interfaces | Access modifiers (private/public) |
Exception Handling
Exception handling lets a program respond gracefully to runtime errors instead of crashing.
Error vs Exception
| Basis | Error | Exception |
|---|---|---|
| Recoverable? | Usually not | Yes, can be handled |
| When it occurs | Compile time or serious runtime failure | Runtime, expected to be caught |
What is Exception Handling?
Keywords
| Keyword | Role |
|---|---|
try | Wraps the risky code that might fail |
throw | Signals that an exception has occurred |
catch | Handles the thrown exception |
try {
throw 1;
} catch (int e) {
cout << "Caught: " << e;
}
- Risky code goes inside
try. throwraises the exception.- One
tryblock can have multiplecatchblocks. catch(...)catches every type of exception.
STL Introduction
The Standard Template Library is a collection of ready-made, reusable tools that ship with C++.
Components of STL
Vector
A dynamic array that resizes itself automatically.
#include <vector>
vector<int> v;
Common Functions
| Function | What It Does |
|---|---|
push_back() | Adds an element at the end |
pop_back() | Removes the last element |
size() | Returns the number of elements |
empty() | Returns true if there are no elements |
clear() | Removes all elements |
front() | Returns the first element |
back() | Returns the last element |
at(index) | Returns the element at index, with bounds checking |
Pair
A simple container that bundles exactly two values together.
#include <utility>
pair<int, string> p;
.firststores the first value..secondstores the second value.
Set & Unordered Set
Both store unique elements — but with very different internal behavior.
Set
#include <set>
set<int> s;
Unordered Set
#include <unordered_set>
unordered_set<int> us;
Common Functions (both)
| Function | What It Does |
|---|---|
insert() | Adds an element (duplicates ignored) |
erase() | Removes an element |
find() | Returns an iterator to an element if found |
count() | Returns 1 if the element exists, else 0 |
size() | Returns the number of elements |
empty() | Returns true if there are no elements |
Set vs Unordered Set
| Basis | Set | Unordered Set |
|---|---|---|
| Order | Sorted | Unsorted |
| Internal structure | Tree-based | Hash-table based |
| Speed | Slower | Faster (average) |
Map & Unordered Map
Both store key-value pairs — the same sorted-vs-hashed distinction as sets.
Map
#include <map>
map<int, string> mp;
Unordered Map
#include <unordered_map>
unordered_map<int, string> ump;
Common Functions (both)
| Function | What It Does |
|---|---|
insert({key, value}) | Adds a key-value pair |
erase() | Removes a pair using its key |
find() | Searches for a key |
count() | Returns 1 if the key exists, else 0 |
size() | Returns the number of pairs |
empty() | Returns true if there are no pairs |
[key] | Accesses or updates a value by key |
If the key doesn't exist, the [] operator creates it with a default value.
Map vs Unordered Map
| Basis | Map | Unordered Map |
|---|---|---|
| Keys | Sorted | Unsorted |
| Internal structure | Tree-based | Hash-table based |
| Speed | Slower | Faster (average) |
Iterators
Iterators are how you move through the elements inside any STL container.
vector<int>::iterator it;
Functions
| Function | What It Does |
|---|---|
begin() | Points to the first element |
end() | Points just past the last element |
rbegin() | Points to the last element (reverse) |
rend() | Points just before the first element (reverse) |
auto lets the compiler automatically determine the data type of a variable from its value — handy for long iterator types.
Algorithms
Ready-made STL functions that operate on containers, so you don't have to write them yourself.
sort(v.begin(), v.end());
Common Algorithms
| Function | What It Does |
|---|---|
sort() | Sorts elements in ascending order by default |
reverse() | Reverses the order of elements |
swap() | Swaps the values of two variables |
max() / min() | Returns the larger / smaller of two values |
max_element() | Returns an iterator to the largest element |
min_element() | Returns an iterator to the smallest element |
find() | Searches for a value in a range |
count() | Counts occurrences of a value |
binary_search() | Checks if a value exists (needs a sorted container) |
lower_bound() | Returns an iterator to the first element ≥ value |
upper_bound() | Returns an iterator to the first element > value |