CPP Programming
This C++ cheatsheet provides a quick
Complete C++ Programming Cheatsheet
A comprehensive reference guide to C++ programming, covering fundamental concepts, syntax, data types, operators, control structures, arrays, strings, functions, pointers, object-oriented programming, inheritance, polymorphism, STL, file handling, exception handling, and advanced C++ concepts.
1. Introduction to C++
C++ is a general-purpose, compiled programming language developed by Bjarne Stroustrup at Bell Laboratories. It was initially known as C with Classes.
C++ supports procedural, object-oriented, and generic programming.
Features of C++
- Object-oriented programming.
- High performance and efficiency.
- Supports procedural programming.
- Supports generic programming through templates.
- Supports function and operator overloading.
- Provides dynamic memory management.
- Rich Standard Template Library (STL).
- Supports exception handling.
- Compatible with many C programming concepts.
Applications of C++
- Operating systems
- Game development
- Desktop applications
- Embedded systems
- Robotics and IoT
- Database systems
- Compilers
- High-performance computing
- Cybersecurity tools
- Competitive programming
File Extensions
| Extension | Description |
|---|---|
.cpp | C++ source file |
.cc | C++ source file |
.cxx | C++ source file |
.h | Header file |
.hpp | C++ header file |
.o | Object file |
.exe | Windows executable |
2. Structure of a C++ Program
#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }
Explanation
| Component | Description |
|---|---|
#include | Includes header files |
<iostream> | Input/output stream library |
using namespace std | Makes standard namespace names available |
int main() | Main function |
{ } | Defines a block |
cout | Displays output |
return 0 | Indicates successful execution |
; | Terminates a statement |
Compilation Using GCC
g++ program.cpp -o program ./program
Compile using C++17:
g++ -std=c++17 -Wall -Wextra -g program.cpp -o program
Compile using C++20:
g++ -std=c++20 -Wall -Wextra program.cpp -o program
3. Tokens and Keywords
Tokens are the smallest individual elements of a C++ program.
Types of Tokens
| Token | Example |
|---|---|
| Keywords | int, class, return |
| Identifiers | total, student |
| Constants | 10, 3.14 |
| String literals | "Hello" |
| Operators | +, -, * |
| Punctuators | ;, {}, () |
Identifier Rules
- Must begin with a letter or underscore.
- Cannot begin with a digit.
- Cannot contain spaces.
- Cannot use reserved keywords.
- C++ is case-sensitive.
int total; int _number; int marks1; // Invalid: // int 1marks; // int my marks; // int class;
Common C++ Keywords
| Category | Keywords |
|---|---|
| Data types | int, char, float, double, void, bool |
| Decision-making | if, else, switch, case, default |
| Loops | for, while, do |
| Jump statements | break, continue, goto, return |
| OOP | class, public, private, protected, this |
| Inheritance | virtual, override, final |
| Memory | new, delete |
| Templates | template, typename |
| Exception handling | try, catch, throw |
| Other | const, static, extern, sizeof, namespace, using, auto, nullptr |
4. Data Types
Data types specify the kind of data a variable can store.
4.1 Fundamental Data Types
| Data Type | Typical Size | Example |
|---|---|---|
bool | 1 byte | true |
char | 1 byte | 'A' |
int | 4 bytes | 100 |
float | 4 bytes | 10.5f |
double | 8 bytes | 25.567 |
long double | Platform-dependent | 12.345L |
void | No value | void |
Note: Sizes are implementation-dependent except for sizeof(char), which is always 1 byte.
4.2 Type Modifiers
| Modifier | Description |
|---|---|
signed | Positive and negative values |
unsigned | Non-negative values |
short | Short integer type |
long | Extended integer type |
long long | At least 64-bit integer range |
short int a = 10; long int b = 100000; long long int c = 123456789; unsigned int d = 50; signed int e = -20;
4.3 Derived Data Types
- Arrays
- Pointers
- References
- Functions
4.4 User-Defined Data Types
- Class
- Structure
- Union
- Enumeration
- Type aliases
5. Variables and Constants
5.1 Variable Declaration
int age; float salary; char grade; string name;
5.2 Variable Initialization
int age = 22; float price = 99.50f; char grade = 'A'; string name = "Uday";
5.3 Multiple Variable Declaration
int a = 10, b = 20, c = 30;
5.4 Constants Using const
const float PI = 3.14159f;
5.5 Constants Using constexpr
constexpr int MAX = 100;
constexpr allows expressions to be evaluated at compile time when their requirements are satisfied.
5.6 Auto Keyword
Automatically deduces the variable's type.
auto a = 10; auto b = 10.5; auto name = "Uday";
6. Input and Output
Header file: <iostream>
6.1 cout
Displays output.
cout << "Hello World";
6.2 cin
Accepts input.
int age; cin >> age;
6.3 getline()
Reads an entire line, including spaces.
string name; getline(cin, name); cout << name;
6.4 cerr
Displays error messages.
cerr << "Error occurred!";
6.5 clog
Displays logging information.
clog << "Program started";
6.6 Input and Output Operators
| Operator | Purpose |
|---|---|
<< | Insertion operator |
>> | Extraction operator |
Example:
#include <iostream> using namespace std; int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; cout << "Sum = " << a + b; return 0; }
7. Escape Sequences
| Escape Sequence | Meaning |
|---|---|
\n | New line |
\t | Horizontal tab |
\b | Backspace |
\r | Carriage return |
\a | Alert/bell |
\\ | Backslash |
\' | Single quotation mark |
\" | Double quotation mark |
\0 | Null character |
\v | Vertical tab |
\f | Form feed |
Example:
cout << "Hello\nWorld"; cout << "Name:\tUday"; cout << "\"C++ Programming\"";
8. Operators
Operators perform operations on variables and values.
8.1 Arithmetic Operators
| Operator | Operation | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
int a = 10, b = 3; cout << a + b; // 13 cout << a / b; // 3 cout << a % b; // 1
8.2 Relational Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
8.3 Logical Operators
| Operator | Meaning |
|---|---|
&& | Logical AND |
| ` | |
! | Logical NOT |
int age = 20; if (age >= 18 && age <= 60) { cout << "Eligible"; }
8.4 Assignment Operators
| Operator | Example | Equivalent |
|---|---|---|
= | a = 5 | Assign |
+= | a += 5 | a = a + 5 |
-= | a -= 5 | a = a - 5 |
*= | a *= 5 | a = a * 5 |
/= | a /= 5 | a = a / 5 |
%= | a %= 5 | a = a % 5 |
&= | a &= 5 | Bitwise AND assignment |
| ` | =` | `a |
^= | a ^= 5 | Bitwise XOR assignment |
<<= | a <<= 1 | Left shift assignment |
>>= | a >>= 1 | Right shift assignment |
8.5 Increment and Decrement
| Operator | Meaning |
|---|---|
++a | Pre-increment |
a++ | Post-increment |
--a | Pre-decrement |
a-- | Post-decrement |
int a = 5; cout << ++a; // 6 int b = 5; cout << b++; // 5 // b becomes 6
8.6 Bitwise Operators
| Operator | Operation |
|---|---|
& | Bitwise AND |
| ` | ` |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Left shift |
>> | Right shift |
int a = 5; // 0101 int b = 3; // 0011 cout << (a & b); // 1 cout << (a | b); // 7 cout << (a ^ b); // 6 cout << (a << 1); // 10 cout << (a >> 1); // 2
8.7 Conditional (Ternary) Operator
int a = 10, b = 20; int max = (a > b) ? a : b; cout << max;
8.8 Other Operators
| Operator | Purpose |
|---|---|
sizeof | Returns size in bytes |
& | Address-of |
* | Pointer dereference |
. | Member access |
-> | Pointer member access |
:: | Scope resolution |
[] | Array subscript |
() | Function call |
new | Dynamic allocation |
delete | Releases dynamically allocated memory |
9. Operator Precedence
| Priority | Operators | Associativity |
|---|---|---|
| 1 | :: | Left to right |
| 2 | () [] . -> x++ x-- | Left to right |
| 3 | ++x --x ! ~ sizeof * & new delete | Right to left |
| 4 | .* ->* | Left to right |
| 5 | * / % | Left to right |
| 6 | + - | Left to right |
| 7 | << >> | Left to right |
| 8 | < <= > >= | Left to right |
| 9 | == != | Left to right |
| 10 | & | Left to right |
| 11 | ^ | Left to right |
| 12 | ` | ` |
| 13 | && | Left to right |
| 14 | ` | |
| 15 | ?: | Right to left |
| 16 | Assignment operators | Right to left |
| 17 | , | Left to right |
10. Type Conversion
Type conversion changes a value from one data type to another.
10.1 Implicit Type Conversion
Automatically performed by the compiler.
int a = 10; double b = 5.5; double result = a + b;
10.2 C-Style Casting
int a = 10, b = 3; double result = (double)a / b;
10.3 static_cast
int a = 10; double result = static_cast<double>(a);
10.4 dynamic_cast
Used for checked conversions in polymorphic class hierarchies.
Base* base = new Derived; Derived* derived = dynamic_cast<Derived*>(base); delete base;
10.5 const_cast
Adds or removes const/volatile qualification.
const int a = 10; const int* p = &a;
Use care: modifying an object originally declared const through a cast is undefined behavior.
10.6 reinterpret_cast
Performs low-level reinterpretation of pointer or integer values where permitted.
int a = 10; int* ptr = &a; uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
Requires <cstdint> for uintptr_t where supported.
11. Decision-Making Statements
11.1 if Statement
if (condition) { // Statements }
11.2 if-else Statement
if (condition) { // True block } else { // False block }
11.3 else-if Ladder
int marks = 75; if (marks >= 90) { cout << "Grade A"; } else if (marks >= 75) { cout << "Grade B"; } else if (marks >= 50) { cout << "Grade C"; } else { cout << "Fail"; }
11.4 Nested if
if (age >= 18) { if (age <= 60) { cout << "Eligible"; } }
11.5 switch Statement
int choice = 2; switch (choice) { case 1: cout << "One"; break; case 2: cout << "Two"; break; case 3: cout << "Three"; break; default: cout << "Invalid choice"; }
11.6 Modern switch Initializer (C++17)
switch (int value = 2; value) { case 1: cout << "One"; break; case 2: cout << "Two"; break; }
12. Looping Statements
12.1 for Loop
for (int i = 1; i <= 5; i++) { cout << i << endl; }
12.2 while Loop
int i = 1; while (i <= 5) { cout << i << endl; i++; }
12.3 do-while Loop
int i = 1; do { cout << i << endl; i++; } while (i <= 5);
12.4 Range-Based for Loop
int arr[] = {10, 20, 30, 40}; for (int x : arr) { cout << x << endl; }
12.5 Nested Loop
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { cout << "* "; } cout << endl; }
12.6 Loop Control Statements
| Statement | Purpose |
|---|---|
break | Terminates nearest loop |
continue | Skips current iteration |
goto | Transfers control to a labeled statement |
return | Exits a function |
13. Arrays
An array stores multiple values of the same data type in contiguous memory.
13.1 One-Dimensional Array
int numbers[5] = {10, 20, 30, 40, 50}; cout << numbers[0];
13.2 Array Input and Output
#include <iostream> using namespace std; int main() { int arr[5]; for (int i = 0; i < 5; i++) { cin >> arr[i]; } for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }
13.3 Two-Dimensional Array
int matrix[2][2] = { {1, 2}, {3, 4} }; cout << matrix[0][1];
13.4 Matrix Traversal
for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cout << matrix[i][j] << " "; } cout << endl; }
13.5 Three-Dimensional Array
int arr[2][3][4];
13.6 Important Array Operations
- Traversal
- Insertion
- Deletion
- Searching
- Sorting
- Reversing
- Merging
13.7 STL Array
Header file: <array>
#include <array> array<int, 5> arr = {10, 20, 30, 40, 50}; cout << arr.size(); cout << arr.at(0);
14. Strings
C++ provides two common ways to work with strings.
14.1 C-Style Strings
char name[20] = "Uday"; cout << name;
14.2 C++ String
Header file: <string>
#include <iostream> #include <string> using namespace std; int main() { string name = "Uday"; cout << name; return 0; }
14.3 String Input
string name; cin >> name;
Reads one word.
For complete lines:
string name; getline(cin, name);
14.4 Common String Functions
| Function | Purpose |
|---|---|
length() | Returns string length |
size() | Returns string size |
empty() | Checks whether string is empty |
append() | Adds text |
clear() | Removes all characters |
substr() | Extracts substring |
find() | Finds a substring or character |
replace() | Replaces part of a string |
erase() | Removes characters |
insert() | Inserts characters |
compare() | Compares strings |
at() | Accesses character with bounds checking |
push_back() | Adds one character |
pop_back() | Removes last character |
Example:
string str = "Hello"; cout << str.length(); str.append(" World"); cout << str; cout << str.substr(0, 5);
15. Functions
A function is a reusable block of code that performs a specific task.
15.1 Function Declaration
int add(int, int);
15.2 Function Definition
int add(int a, int b) { return a + b; }
15.3 Function Calling
int result = add(10, 20);
Complete Example
#include <iostream> using namespace std; int add(int, int); int main() { int result = add(10, 20); cout << "Sum = " << result; return 0; } int add(int a, int b) { return a + b; }
15.4 Types of Functions
| Type | Arguments | Return Value |
|---|---|---|
| 1 | No | No |
| 2 | Yes | No |
| 3 | No | Yes |
| 4 | Yes | Yes |
15.5 Default Arguments
int add(int a, int b = 10) { return a + b; } cout << add(5); // 15 cout << add(5, 5); // 10
15.6 Inline Functions
inline int square(int x) { return x * x; }
15.7 Function Prototypes
A function prototype declares the function before its use.
int multiply(int, int);
15.8 Pass by Value
void change(int x) { x = 100; }
The original variable is not changed.
15.9 Pass by Reference
void change(int &x) { x = 100; }
The original variable is modified.
15.10 Pass by Pointer
void change(int *x) { if (x != nullptr) { *x = 100; } }
16. Recursion
Recursion occurs when a function calls itself.
Factorial Using Recursion
int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }
Fibonacci Using Recursion
int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }
Important: Always define a base condition to prevent infinite recursion.
17. Pointers
A pointer stores the memory address of another object.
17.1 Pointer Declaration
int *ptr;
17.2 Pointer Initialization
int a = 10; int *ptr = &a;
17.3 Dereferencing
cout << *ptr;
17.4 Pointer Example
#include <iostream> using namespace std; int main() { int a = 10; int *ptr = &a; cout << "Value: " << a << endl; cout << "Address: " << ptr << endl; cout << "Dereferenced value: " << *ptr << endl; return 0; }
17.5 NULL and nullptr
int *p1 = nullptr;
nullptr is the modern C++ null pointer literal.
17.6 Pointer to Pointer
int a = 10; int *p = &a; int **pp = &p; cout << **pp;
17.7 Pointer Arithmetic
int arr[] = {10, 20, 30}; int *p = arr; cout << *p << endl; cout << *(p + 1) << endl; cout << *(p + 2) << endl;
17.8 Array of Pointers
int a = 10, b = 20, c = 30; int *arr[] = {&a, &b, &c}; cout << *arr[0];
17.9 Function Pointer
int add(int a, int b) { return a + b; } int (*ptr)(int, int) = add; cout << ptr(10, 20);
18. References
A reference is another name for an existing variable.
18.1 Reference Declaration
int a = 10; int &ref = a;
18.2 Modifying Through Reference
int a = 10; int &ref = a; ref = 50; cout << a; // 50
18.3 Reference as Function Argument
void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
18.4 Constant Reference
const string &name = someString;
Prevents modification through that reference.
Pointer vs Reference
| Pointer | Reference |
|---|---|
| Stores an address | Acts as an alias |
| Can be null | Must be initialized |
| Can be reassigned | Cannot be reseated |
Uses * for dereferencing | Used directly |
| Supports pointer arithmetic | No pointer arithmetic |
19. Dynamic Memory Allocation
C++ provides new and delete for dynamic memory management.
19.1 new Operator
int *ptr = new int; *ptr = 100; cout << *ptr;
19.2 delete Operator
delete ptr; ptr = nullptr;
19.3 Dynamic Array
int *arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i + 1; } delete[] arr; arr = nullptr;
19.4 Dynamic Object
class Student { public: int roll; }; Student *s = new Student; s->roll = 101; delete s;
19.5 Smart Pointers
Header file: <memory>
#include <memory> auto ptr = make_unique<int>(100); cout << *ptr;
Common smart pointers:
| Smart Pointer | Purpose |
|---|---|
unique_ptr | Exclusive ownership |
shared_ptr | Shared ownership |
weak_ptr | Non-owning reference to shared object |
Prefer smart pointers and standard containers over manual memory management when possible.
20. Object-Oriented Programming
Object-Oriented Programming (OOP) organizes programs around classes and objects.
Four Main Pillars of OOP
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
Benefits of OOP
- Code reusability
- Data security
- Modularity
- Maintainability
- Flexibility
- Easier development of large applications
21. Classes and Objects
21.1 Class
A class is a user-defined blueprint for creating objects.
class Student { public: int roll; string name; void display() { cout << roll << " " << name; } };
21.2 Object
An object is an instance of a class.
Student s1; s1.roll = 101; s1.name = "Uday"; s1.display();
21.3 Access Specifiers
| Access Specifier | Description |
|---|---|
public | Accessible from anywhere permitted by the object |
private | Accessible within the class and its friends |
protected | Accessible within the class, friends, and derived classes |
21.4 Complete Class Example
#include <iostream> using namespace std; class Student { private: int roll; public: void setRoll(int r) { roll = r; } void display() { cout << "Roll: " << roll; } }; int main() { Student s1; s1.setRoll(101); s1.display(); return 0; }
22. Constructors and Destructors
22.1 Constructor
A constructor is a special member function automatically called when an object is initialized.
class Student { public: Student() { cout << "Constructor called"; } };
22.2 Default Constructor
class Student { public: Student() { cout << "Default Constructor"; } };
22.3 Parameterized Constructor
class Student { public: int roll; Student(int r) { roll = r; } };
22.4 Copy Constructor
class Student { public: int roll; Student(const Student &s) { roll = s.roll; } };
22.5 Constructor Overloading
class Student { public: Student() { cout << "Default"; } Student(int x) { cout << x; } };
22.6 Destructor
A destructor is called when an object is destroyed.
class Student { public: ~Student() { cout << "Destructor called"; } };
Constructor vs Destructor
| Constructor | Destructor |
|---|---|
| Initializes an object | Cleans up an object |
| Same name as class | Same name with ~ |
| Can be overloaded | Cannot be overloaded |
| May have parameters | Has no parameters |
| Called during initialization | Called during destruction |
23. Encapsulation
Encapsulation means combining data and functions within a class while controlling access to internal data.
Example:
class BankAccount { private: double balance = 0; public: void deposit(double amount) { if (amount > 0) balance += amount; } double getBalance() { return balance; } };
24. Abstraction
Abstraction hides implementation details and exposes essential functionality.
Example:
class ATM { public: void withdraw() { cout << "Withdrawal process"; } };
Users interact with the public interface without needing to understand its internal implementation.
Abstract Class
An abstract class has at least one pure virtual function.
class Shape { public: virtual void draw() = 0; };
An abstract class cannot be instantiated directly.
25. Inheritance
Inheritance allows one class to acquire the properties and behaviors of another class.
25.1 Single Inheritance
class Animal { public: void eat() { cout << "Eating"; } }; class Dog : public Animal { public: void bark() { cout << "Barking"; } };
25.2 Multilevel Inheritance
class A { public: void showA() {} }; class B : public A { public: void showB() {} }; class C : public B { public: void showC() {} };
25.3 Multiple Inheritance
class A { }; class B { }; class C : public A, public B { };
25.4 Hierarchical Inheritance
class Animal { }; class Dog : public Animal { }; class Cat : public Animal { };
25.5 Hybrid Inheritance
A combination of two or more inheritance types.
Types of Inheritance
| Type | Description |
|---|---|
| Single | One base and one derived class |
| Multiple | Multiple base classes |
| Multilevel | A class derived from another derived class |
| Hierarchical | Multiple derived classes from one base class |
| Hybrid | Combination of inheritance types |
Inheritance Access Modes
| Base Member | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|
| Public | Public | Protected | Private |
| Protected | Protected | Protected | Private |
| Private | Not directly accessible | Not directly accessible | Not directly accessible |
26. Polymorphism
Polymorphism means one interface can represent multiple forms of behavior.
Types of Polymorphism
- Compile-time polymorphism
- Runtime polymorphism
Compile-Time Polymorphism
- Function overloading
- Operator overloading
- Templates
Runtime Polymorphism
- Virtual functions
- Function overriding with virtual dispatch
27. Function Overloading
Multiple functions can have the same name but different parameter lists.
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int main() { cout << add(10, 20) << endl; cout << add(2.5, 3.5); return 0; }
Note: Functions cannot be overloaded only by changing their return type.
28. Operator Overloading
Operator overloading allows operators to work with user-defined types.
Example:
#include <iostream> using namespace std; class Number { public: int value; Number(int v) : value(v) {} Number operator+(const Number &n) { return Number(value + n.value); } }; int main() { Number a(10), b(20); Number c = a + b; cout << c.value; return 0; }
Common overloadable operators:
+-*/==!=<>++--[]()<<>>
Some operators, including ::, ., .*, ?:, and sizeof, cannot be overloaded.
29. Virtual Functions
Virtual functions support runtime polymorphism.
#include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal sound"; } virtual ~Animal() = default; }; class Dog : public Animal { public: void sound() override { cout << "Dog barks"; } }; int main() { Dog d; Animal *ptr = &d; ptr->sound(); return 0; }
Output:
Dog barks
Important Concepts
| Concept | Description |
|---|---|
virtual | Enables dynamic dispatch |
override | Verifies that a function overrides a base virtual function |
final | Prevents further overriding or inheritance |
| Pure virtual function | Declared with = 0 |
| Abstract class | Class with at least one pure virtual function |
30. Friend Functions
A friend function can access private and protected members of a class.
#include <iostream> using namespace std; class Box { private: int value = 100; public: friend void display(Box); }; void display(Box b) { cout << b.value; }
Friend functions are not member functions of the class.
31. Static Members
Static members belong to the class rather than individual objects.
31.1 Static Data Member
class Student { public: static int count; }; int Student::count = 0;
31.2 Static Member Function
class Student { public: static int count; static void display() { cout << count; } }; int Student::count = 10;
Call using:
Student::display();
32. Templates
Templates support generic programming by allowing functions and classes to work with different data types.
32.1 Function Template
template <typename T> T add(T a, T b) { return a + b; } int main() { cout << add(10, 20) << endl; cout << add(2.5, 3.5); }
32.2 Class Template
template <typename T> class Box { public: T value; Box(T v) { value = v; } };
Usage:
Box<int> b1(100); Box<string> b2("Hello");
32.3 Multiple Template Parameters
template <typename T, typename U> class Pair { public: T first; U second; };
32.4 Template Specialization
template <typename T> class Data { }; template <> class Data<int> { };
33. Exception Handling
Exception handling manages runtime errors using try, catch, and throw.
33.1 try and catch
try { int age = -1; if (age < 0) throw age; } catch (int e) { cout << "Invalid age"; }
33.2 Multiple catch Blocks
try { throw 10; } catch (int e) { cout << "Integer exception"; } catch (double e) { cout << "Double exception"; } catch (...) { cout << "Unknown exception"; }
33.3 Standard Exceptions
Header file: <stdexcept>
| Exception | Description |
|---|---|
exception | Base exception class |
runtime_error | Runtime error |
logic_error | Logic error |
invalid_argument | Invalid argument |
out_of_range | Out-of-range access |
length_error | Length-related error |
bad_alloc | Memory allocation failure |
Example:
#include <iostream> #include <stdexcept> using namespace std; int main() { try { throw runtime_error("Something went wrong"); } catch (const exception &e) { cout << e.what(); } return 0; }
34. File Handling
C++ provides file handling through the <fstream> library.
34.1 File Stream Classes
| Class | Purpose |
|---|---|
ifstream | Reads files |
ofstream | Writes files |
fstream | Reads and writes files |
34.2 Writing to a File
#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("data.txt"); if (!file) return 1; file << "Hello C++ Programming"; file.close(); return 0; }
34.3 Reading from a File
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file("data.txt"); if (!file) return 1; string line; while (getline(file, line)) { cout << line << endl; } file.close(); return 0; }
34.4 File Opening Modes
| Mode | Description |
|---|---|
ios::in | Read |
ios::out | Write |
ios::app | Append |
ios::ate | Open and position at end |
ios::trunc | Truncate existing contents |
ios::binary | Binary mode |
34.5 Important File Functions
| Function | Purpose |
|---|---|
open() | Opens a file |
close() | Closes a file |
is_open() | Checks whether a file is open |
getline() | Reads a line |
get() | Reads a character |
put() | Writes a character |
read() | Reads binary data |
write() | Writes binary data |
seekg() | Changes input position |
seekp() | Changes output position |
tellg() | Returns input position |
tellp() | Returns output position |
eof() | Checks end-of-file state |
35. Standard Template Library (STL)
STL is a collection of generic classes and functions for common programming tasks.
Main Components
- Containers
- Iterators
- Algorithms
- Function objects
35.1 Vector
Header: <vector>
A dynamic array.
#include <vector> vector<int> v = {10, 20, 30}; v.push_back(40); v.pop_back(); cout << v.size(); cout << v[0];
Common functions:
| Function | Purpose |
|---|---|
push_back() | Adds an element |
pop_back() | Removes last element |
size() | Returns number of elements |
empty() | Checks whether empty |
clear() | Removes all elements |
at() | Accesses with bounds checking |
front() | First element |
back() | Last element |
begin() | Iterator to first element |
end() | Iterator past last element |
insert() | Inserts elements |
erase() | Removes elements |
35.2 Array
Header: <array>
#include <array> array<int, 3> arr = {10, 20, 30}; cout << arr.size();
35.3 List
Header: <list>
Doubly linked list.
#include <list> list<int> l = {10, 20, 30}; l.push_front(5); l.push_back(40); l.pop_front();
35.4 Forward List
Header: <forward_list>
Singly linked list.
#include <forward_list> forward_list<int> l = {10, 20, 30}; l.push_front(5);
35.5 Deque
Header: <deque>
Double-ended queue.
#include <deque> deque<int> d = {10, 20, 30}; d.push_front(5); d.push_back(40);
35.6 Stack
Header: <stack>
Follows LIFO (Last In, First Out).
#include <stack> stack<int> s; s.push(10); s.push(20); cout << s.top(); s.pop();
35.7 Queue
Header: <queue>
Follows FIFO (First In, First Out).
#include <queue> queue<int> q; q.push(10); q.push(20); cout << q.front(); q.pop();
35.8 Priority Queue
Header: <queue>
By default, a max-heap.
#include <queue> priority_queue<int> pq; pq.push(10); pq.push(30); pq.push(20); cout << pq.top(); // 30
Min-heap:
priority_queue<int, vector<int>, greater<int>> pq;
35.9 Set
Header: <set>
Stores unique sorted elements.
#include <set> set<int> s = {30, 10, 20, 10}; s.insert(40); s.erase(10);
35.10 Multiset
Allows duplicate sorted elements.
#include <set> multiset<int> ms = {10, 20, 10};
35.11 Map
Header: <map>
Stores unique sorted key-value pairs.
#include <map> map<int, string> m; m[1] = "Uday"; m[2] = "Rahul"; cout << m[1];
35.12 Multimap
Allows duplicate keys.
#include <map> multimap<int, string> m; m.insert({1, "Uday"}); m.insert({1, "Rahul"});
35.13 Unordered Set
Header: <unordered_set>
Stores unique elements without sorted order.
#include <unordered_set> unordered_set<int> s = {10, 20, 30}; s.insert(40);
35.14 Unordered Map
Header: <unordered_map>
Stores key-value pairs using hashing.
#include <unordered_map> unordered_map<string, int> marks; marks["Uday"] = 90; marks["Rahul"] = 85;
STL Container Comparison
| Container | Data Structure | Main Feature |
|---|---|---|
vector | Dynamic array | Fast random access |
array | Fixed-size array | Fixed capacity |
list | Doubly linked list | Efficient insertion/removal at known positions |
forward_list | Singly linked list | Forward-only traversal |
deque | Double-ended array | Efficient operations at both ends |
stack | Adapter | LIFO |
queue | Adapter | FIFO |
priority_queue | Heap adapter | Highest priority first by default |
set | Balanced tree | Unique sorted values |
multiset | Balanced tree | Duplicate sorted values |
map | Balanced tree | Unique sorted keys |
multimap | Balanced tree | Duplicate sorted keys |
unordered_set | Hash table | Unique unordered values |
unordered_map | Hash table | Unique unordered keys |
36. Iterators
Iterators provide a way to access elements of STL containers.
Types of Iterators
| Type | Description |
|---|---|
| Input | Reads elements |
| Output | Writes elements |
| Forward | Moves forward |
| Bidirectional | Moves forward and backward |
| Random access | Supports direct movement |
| Contiguous | Provides contiguous storage traversal |
Iterator Example
#include <iostream> #include <vector> using namespace std; int main() { vector<int> v = {10, 20, 30}; for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << " "; } return 0; }
Range-Based Loop
for (int x : v) { cout << x << " "; }
37. Lambda Expressions
Lambda expressions create anonymous functions.
Syntax:
[capture](parameters) -> return_type { // Statements };
Example:
auto add = [](int a, int b) { return a + b; }; cout << add(10, 20);
Lambda with Capture
int x = 10; auto show = [x]() { cout << x; }; show();
Lambda Capture Types
| Capture | Meaning |
|---|---|
[] | No capture |
[=] | Capture used variables by value |
[&] | Capture used variables by reference |
[x] | Capture x by value |
[&x] | Capture x by reference |
[this] | Capture current object pointer |
38. Namespaces
Namespaces organize code and prevent naming conflicts.
Namespace Declaration
namespace MySpace { int value = 100; }
Accessing Namespace Members
cout << MySpace::value;
using Declaration
using std::cout; using std::endl;
using Namespace
using namespace std;
Avoid unnecessarily importing entire namespaces in header files.
39. Preprocessor Directives
Preprocessor directives are processed before compilation.
39.1 #include
#include <iostream> #include "myheader.h"
39.2 #define
#define PI 3.14159 #define SQUARE(x) ((x) * (x))
39.3 #undef
#undef PI
39.4 Conditional Compilation
#ifdef DEBUG cout << "Debug mode"; #endif
Other directives:
#if #elif #else #endif #ifndef
39.5 Header Guards
#ifndef MYHEADER_H #define MYHEADER_H void display(); #endif
39.6 pragma once
#pragma once
Commonly used to prevent repeated inclusion, although it is not part of the C++ standard.
40. Type Modifiers and Storage
40.1 Type Modifiers
| Modifier | Purpose |
|---|---|
signed | Signed numeric values |
unsigned | Non-negative integer values |
short | Short integer type |
long | Extended integer type |
40.2 Storage Class and Related Keywords
| Keyword | Purpose |
|---|---|
auto | Automatic type deduction in modern C++ |
static | Static storage duration or class-level member |
extern | External linkage declaration |
register | Deprecated storage-class specifier |
thread_local | Thread-local storage duration |
mutable | Allows modification of selected members in const objects |
const | Prevents modification through an identifier |
volatile | Indicates potentially externally changing data |
41. Modern C++ Features
41.1 auto
auto x = 10; auto name = string("Uday");
41.2 nullptr
int *ptr = nullptr;
41.3 Range-Based for
for (int x : arr) { cout << x; }
41.4 Smart Pointers
auto ptr = make_unique<int>(100);
41.5 Move Semantics
#include <utility> string a = "Hello"; string b = move(a);
std::move enables move operations; it does not itself move data.
41.6 Structured Bindings (C++17)
pair<int, string> p = {1, "Uday"}; auto [id, name] = p;
41.7 Optional (C++17)
#include <optional> optional<int> value = 10;
41.8 Null Coalescing Alternative
C++ does not have a built-in ?? operator. Use conditional expressions or optional::value_or().
optional<int> value; int result = value.value_or(0);
41.9 constexpr
constexpr int square(int x) { return x * x; }
41.10 Concepts (C++20)
#include <concepts> template <typename T> requires integral<T> T add(T a, T b) { return a + b; }
41.11 Ranges (C++20)
#include <ranges> #include <vector> vector<int> v = {1, 2, 3, 4, 5}; for (int x : v | views::filter([](int n) { return n % 2 == 0; })) { cout << x << " "; }
42. Important Standard Libraries
| Header | Purpose |
|---|---|
<iostream> | Input and output |
<iomanip> | Output formatting |
<string> | String handling |
<vector> | Dynamic arrays |
<array> | Fixed-size arrays |
<list> | Doubly linked list |
<forward_list> | Singly linked list |
<deque> | Double-ended queue |
<stack> | Stack |
<queue> | Queue and priority queue |
<set> | Set and multiset |
<map> | Map and multimap |
<unordered_set> | Hash-based set |
<unordered_map> | Hash-based map |
<algorithm> | Sorting and algorithms |
<numeric> | Numeric algorithms |
<iterator> | Iterator utilities |
<functional> | Function objects |
<memory> | Smart pointers |
<fstream> | File handling |
<sstream> | String streams |
<cmath> | Mathematical functions |
<cstdlib> | General utilities |
<cstring> | C-style string functions |
<cctype> | Character handling |
<ctime> | Date and time |
<random> | Random number generation |
<stdexcept> | Standard exceptions |
<exception> | Exception support |
<utility> | Pair, move, swap |
<optional> | Optional values |
<variant> | Type-safe alternatives |
<tuple> | Multiple-value objects |
<thread> | Thread support |
<mutex> | Synchronization |
<filesystem> | Filesystem operations |
43. Common Programming Problems
| Problem | Basic Logic |
|---|---|
| Even or odd | n % 2 == 0 |
| Positive or negative | Compare with zero |
| Largest of two numbers | Compare values |
| Largest of three numbers | Multiple comparisons |
| Swap two numbers | Temporary variable |
| Factorial | Repeated multiplication |
| Prime number | Check divisors up to square root |
| Fibonacci series | Add previous two terms |
| Reverse a number | Extract digits using % 10 |
| Palindrome number | Compare with reversed number |
| Armstrong number | Sum digits raised to number of digits |
| Sum of digits | Repeated % 10 |
| Count digits | Repeated division by 10 |
| GCD | Euclidean algorithm |
| LCM | a / gcd(a,b) * b for nonzero inputs |
43.1 Even or Odd
if (n % 2 == 0) cout << "Even"; else cout << "Odd";
43.2 Factorial
int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; }
43.3 Prime Number
bool isPrime = true; if (n <= 1) { isPrime = false; } else { for (int i = 2; i <= n / i; i++) { if (n % i == 0) { isPrime = false; break; } } } cout << (isPrime ? "Prime" : "Not Prime");
44. Pattern Programs
44.1 Square Pattern
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { cout << "* "; } cout << endl; }
Output:
* * * * * * * * * * * * * * * * * * * * * * * * *
44.2 Right Triangle
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; }
44.3 Inverted Triangle
for (int i = 5; i >= 1; i--) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; }
44.4 Number Triangle
for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { cout << j << " "; } cout << endl; }
45. Time and Space Complexity
Complexity describes the efficiency of an algorithm.
Common Time Complexities
| Complexity | Name | Example |
|---|---|---|
| O(1) | Constant | Array element access |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Array traversal |
| O(n log n) | Linearithmic | Merge sort |
| O(n²) | Quadratic | Bubble sort |
| O(n³) | Cubic | Basic triple nested loops |
| O(2ⁿ) | Exponential | Naive recursive Fibonacci |
| O(n!) | Factorial | Brute-force permutations |
Common Sorting Algorithms
| Algorithm | Average Time | Worst Time |
|---|---|---|
| Bubble Sort | O(n²) | O(n²) |
| Selection Sort | O(n²) | O(n²) |
| Insertion Sort | O(n²) | O(n²) |
| Merge Sort | O(n log n) | O(n log n) |
| Quick Sort | O(n log n) | O(n²) |
| Heap Sort | O(n log n) | O(n log n) |
Searching Algorithms
| Algorithm | Average/Worst Time |
|---|---|
| Linear Search | O(n) |
| Binary Search | O(log n) |
Binary search requires sorted data.
46. Common Errors
| Error | Meaning |
|---|---|
| Syntax error | Incorrect syntax |
| Runtime error | Error during execution |
| Logical error | Incorrect program output |
| Linker error | Problem linking components |
| Compilation error | Compiler cannot compile source code |
| Segmentation fault | Invalid memory access |
Common Mistakes
// Missing semicolon int a = 10 // Assignment instead of comparison if (a = 10) // Uninitialized pointer int *ptr; *ptr = 10; // Array out of bounds int arr[5]; arr[5] = 10;
Correct Versions
int a = 10; if (a == 10) { cout << "Equal"; } int *ptr = nullptr; int arr[5]; arr[4] = 10;
47. Quick Syntax Reference
| Task | Syntax |
|---|---|
| Print output | cout << "Hello"; |
| Read input | cin >> a; |
| Read full line | getline(cin, str); |
| Declare integer | int a; |
| Declare float | float a; |
| Declare string | string name; |
| Declare array | int arr[10]; |
| Declare vector | vector<int> v; |
| Declare pointer | int *ptr; |
| Declare reference | int &ref = a; |
| Declare function | int add(int a, int b); |
| Declare class | class Student {}; |
| Create object | Student s1; |
| Allocate memory | new int; |
| Release memory | delete ptr; |
| Open file | ifstream file("data.txt"); |
| Return value | return value; |
| Include library | #include <iostream> |
| Namespace access | std::cout |
48. C++ Best Practices
- Use meaningful variable and function names.
- Initialize variables before using them.
- Use
constwherever appropriate. - Prefer
nullptroverNULL. - Prefer
std::stringover C-style strings for normal text handling. - Prefer
std::vectorover raw dynamic arrays. - Prefer smart pointers over manual memory management.
- Use references when appropriate to avoid unnecessary copies.
- Use
overridewhen overriding virtual functions. - Keep classes and functions small and focused.
- Use exception handling for exceptional conditions.
- Avoid unnecessary global variables.
- Compile with warnings enabled.
- Follow proper indentation and formatting.
- Use standard library algorithms whenever suitable.
- Avoid memory leaks and dangling pointers.
- Use RAII for resource management.
- Write reusable and modular code.
Conclusion
C++ is an important programming language for software development, competitive programming, game development, embedded systems, and system programming.
To master C++:
- Learn fundamental programming concepts.
- Understand operators and control structures.
- Practice arrays, strings, and functions.
- Master pointers and references.
- Understand object-oriented programming.
- Practice inheritance and polymorphism.
- Learn templates and exception handling.
- Master STL containers and algorithms.
- Build practical projects.
Learn. Build. Grow. — Ugenz Academy