🚀 C++ Introduction
🎯 Complete Definition (10 Lines)
C++ is a compiled, statically-typed, multi-paradigm programming language created by
Bjarne Stroustrup in 1985 as "C with Classes". It extends C with object-oriented,
generic, and functional programming features while maintaining performance close to hardware.
Key Features: Zero-cost abstractions, deterministic resource management (RAII),
compile-time computation (templates/constexpr), operator overloading, multiple inheritance,
and direct memory manipulation.
Standards: C++98, C++11, C++14, C++17, C++20, C++23. Used in game engines (Unreal),
browsers (Chrome), databases, trading systems, and operating systems.
#include <iostream>
using namespace std;
int main() {
cout << "⚡ C++ Master Track - CodeOrbitPro\n";
cout << "C++ Version: " << __cplusplus << endl;
return 0;
}
📊 Variables & Data Types
🎯 Complete Definition (10 Lines)
C++ has statically typed variables requiring explicit type declaration.
Types include fundamental types (int, float, double, char, bool), modifiers (signed, unsigned, short, long),
and compound types (arrays, pointers, references).
Memory: auto, register, static, extern, thread_local storage classes. Type sizes
implementation-defined via sizeof(). Type aliases: typedef and using. C++11 adds auto type deduction
and decltype for expression types.
Constants: const (compile-time), constexpr (C++11), consteval (C++20).
Literals: 42, 3.14f, 'A', "text", true/false.
#include <iostream>
using namespace std;
int main() {
int age = 25; // Integer
double price = 99.99; // Double precision
char grade = 'A'; // Character
bool active = true; // Boolean
auto score = 95.5; // auto deduction (C++11)
const float PI = 3.14159f; // Constant
constexpr int MAX = 100; // Compile-time constant
cout << age << " " << price << " " << grade << endl;
return 0;
}
🔢 Operators
🎯 Complete Definition (10 Lines)
C++ operators perform operations on operands. Categories: arithmetic (+, -, *, /, %),
relational (==, !=, <, >), logical (&&, ||, !), bitwise (&, |, ^, ~, <<, >>), assignment (=, +=, -=),
increment/decrement (++, --), member access (., ->), scope resolution (::), conditional (? :).
Overloading: Most operators can be overloaded for user-defined types except
::, .*, ., ?:. Precedence follows C rules. New operators: new/delete for dynamic memory,
sizeof for size, typeid for type information, alignof for alignment.
C++20: Three-way comparison (<=>) operator.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
cout << "Arithmetic: " << a + b << " " << a / b << endl;
cout << "Comparison: " << (a > b) << endl;
cout << "Logical: " << (true && false) << endl;
// Bitwise operations
cout << "Bitwise AND: " << (a & b) << endl;
cout << "Shift left: " << (a << 1) << endl;
// Ternary operator
int max = (a > b) ? a : b;
cout << "Max: " << max << endl;
return 0;
}
🔀 Control Flow
🎯 Complete Definition (10 Lines)
Control flow in C++ includes sequential execution, conditional branching (if-else, switch),
loops (for, while, do-while), and jump statements (break, continue, goto, return).
If-else: Supports nested conditions. Switch: Jump table optimization,
requires integral/enum types, break prevents fall-through.
Loops: for(init; condition; increment), while(condition), do-while (executes at least once).
Range-based for (C++11): for(auto& item : container).
Flow control: break exits loop/switch, continue skips iteration, goto jumps to label,
return exits function.
#include <iostream>
using namespace std;
int main() {
// If-else
int score = 85;
if(score >= 90) cout << "A ⭐\n";
else if(score >= 80) cout << "B ⭐\n";
else cout << "C 📚\n";
// Switch
char grade = 'B';
switch(grade) {
case 'A': cout << "Excellent!\n"; break;
case 'B': cout << "Good!\n"; break;
default: cout << "Needs improvement\n";
}
// Loops
for(int i = 0; i < 5; i++) cout << i << " ";
cout << endl;
int count = 0;
while(count < 3) {
cout << "Count: " << count++ << endl;
}
return 0;
}
⚙️ Functions
🎯 Complete Definition (10 Lines)
Functions are reusable code blocks with return type, name, parameters, and body.
Support pass-by-value, pass-by-reference (&), pass-by-pointer (*).
Features: Default arguments, function overloading (same name, different parameters),
inline functions (suggest inlining), constexpr functions (compile-time evaluation).
Advanced: Lambda expressions (C++11), variadic templates, function pointers,
std::function wrapper. Return type deduction (C++14): auto function(){...}.
Calling conventions: cdecl, stdcall, fastcall. Stack frame management.
#include <iostream>
using namespace std;
// Function declaration
int add(int a, int b);
double add(double a, double b); // Overloading
// Default arguments
void display(string msg = "Hello") {
cout << msg << endl;
}
// Pass by reference
void increment(int& x) {
x++;
}
// Lambda (C++11)
auto multiply = [](int a, int b) { return a * b; };
int main() {
cout << add(5, 3) << endl;
cout << add(2.5, 3.7) << endl;
int num = 10;
increment(num);
cout << "Incremented: " << num << endl;
cout << "Lambda: " << multiply(4, 5) << endl;
return 0;
}
// Function definition
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
📋 Arrays & Vectors
🎯 Complete Definition (10 Lines)
Arrays: Fixed-size contiguous memory, declared as type name[size].
Zero-indexed, sizeof(array) returns total bytes. Multidimensional: type name[rows][cols].
Vectors: Dynamic array from STL (std::vector), resizable, provides size(),
push_back(), pop_back(), insert(), erase(), at() with bounds checking, operator[] without.
Other containers: std::array (C++11 fixed-size), std::list (doubly-linked),
std::deque (double-ended queue). Range-based for loops work with all containers.
Initialization: int arr[] = {1,2,3}; vector v = {4,5,6}; (C++11).
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Static array
int numbers[5] = {1, 2, 3, 4, 5};
cout << "Array size: " << sizeof(numbers)/sizeof(numbers[0]) << endl;
// Vector (dynamic array)
vector scores = {85, 92, 78, 90};
scores.push_back(88); // Add element
scores.pop_back(); // Remove last
cout << "Vector: ";
for(int score : scores) { // Range-based for (C++11)
cout << score << " ";
}
cout << endl;
// 2D vector
vector> matrix = {{1,2}, {3,4}};
return 0;
}
📍 Pointers
🎯 Complete Definition (10 Lines)
Pointers are variables storing memory addresses. Declaration: type* ptr;
& operator gets address, * dereferences pointer. nullptr (C++11) replaces NULL.
Types: Raw pointers, smart pointers (unique_ptr, shared_ptr, weak_ptr in C++11),
function pointers, member pointers.
Operations: Pointer arithmetic (++, --, +, -), comparison, array indexing via pointers,
dynamic allocation with new/delete.
References: Aliases to variables (type& ref = var), must be initialized, cannot be null,
cannot be reassigned. Safer than pointers for parameter passing.
#include <iostream>
#include <memory> // For smart pointers
using namespace std;
int main() {
int x = 42;
int* ptr = &x; // Pointer to x
cout << "Value: " << *ptr << ", Address: " << ptr << endl;
// Dynamic allocation
int* arr = new int[5]; // Heap allocation
for(int i = 0; i < 5; i++) arr[i] = i * 10;
delete[] arr; // Must delete!
// Smart pointers (C++11)
unique_ptr smartPtr = make_unique(100);
cout << "Smart pointer: " << *smartPtr << endl;
// No delete needed - automatically deleted
// Reference
int& ref = x; // Reference to x
ref = 99; // Changes x
cout << "x is now: " << x << endl;
return 0;
}
🏗️ Object Oriented Programming
🎯 Complete Definition (10 Lines)
C++ OOP includes classes, objects, encapsulation, inheritance, polymorphism.
Class: blueprint with data members and member functions.
Access specifiers: public, private, protected. Constructors (default, parameterized, copy),
destructor (~ClassName()), member initialization lists.
Inheritance: Single, multiple, hierarchical, hybrid. Virtual functions enable
runtime polymorphism. Abstract classes have pure virtual functions (= 0).
Special members: friend functions/classes, static members, const members,
mutable members.
#include <iostream>
#include <string>
using namespace std;
// Base class
class Vehicle {
protected:
string brand;
public:
Vehicle(string b) : brand(b) {} // Constructor
virtual void display() { // Virtual function
cout << "Brand: " << brand << endl;
}
virtual ~Vehicle() {} // Virtual destructor
};
// Derived class
class Car : public Vehicle {
private:
int doors;
public:
Car(string b, int d) : Vehicle(b), doors(d) {}
void display() override { // Override (C++11)
cout << "Car - Brand: " << brand << ", Doors: " << doors << endl;
}
};
int main() {
Vehicle* v1 = new Car("Toyota", 4);
v1->display(); // Calls Car::display() (polymorphism)
delete v1;
Car myCar("Honda", 2);
myCar.display();
return 0;
}
🎭 Templates
🎯 Complete Definition (10 Lines)
Templates enable generic programming. Function templates: template
T function(T a, T b). Class templates: template class ClassName {}.
Template specialization: Provide specific implementation for particular types.
Partial specialization for subsets of types.
Variadic templates (C++11): template for variable number of
type parameters. Fold expressions (C++17) simplify variadic template code.
Concepts (C++20): Constraints on template parameters. auto parameters (C++20)
for abbreviated function templates.
#include <iostream>
#include <string>
using namespace std;
// Function template
template
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
// Class template
template
class Container {
private:
T value;
public:
Container(T v) : value(v) {}
T getValue() { return value; }
};
// Variadic template (C++11)
template
void printAll(Args... args) {
(cout << ... << args) << endl; // Fold expression (C++17)
}
int main() {
cout << maxValue(10, 20) << endl;
cout << maxValue(3.14, 2.71) << endl;
Container intBox(42);
Container strBox("Hello");
printAll("Numbers: ", 1, " ", 2, " ", 3);
return 0;
}
📦 Standard Template Library
🎯 Complete Definition (10 Lines)
STL provides containers, algorithms, iterators, and function objects.
Core components work together via iterators as glue.
Containers: Sequence (vector, deque, list, array), associative (set, map,
multiset, multimap), unordered (unordered_set, unordered_map - C++11), container adapters
(stack, queue, priority_queue).
Algorithms: 100+ algorithms in : sort, find, copy, transform,
accumulate, etc. Work on ranges via iterators.
Iterators: Input, output, forward, bidirectional, random access.
begin(), end() functions.
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
using namespace std;
int main() {
// Vector and algorithms
vector numbers = {5, 2, 8, 1, 9};
sort(numbers.begin(), numbers.end());
// Set (unique, sorted)
set uniqueNums = {3, 1, 4, 1, 5};
// Map (key-value)
map scores = {{"Alice", 95}, {"Bob", 88}};
scores["Charlie"] = 92;
// Algorithm examples
auto it = find(numbers.begin(), numbers.end(), 8);
if(it != numbers.end()) cout << "Found 8\n";
// Lambda with algorithm
for_each(numbers.begin(), numbers.end(), [](int n) {
cout << n << " ";
});
cout << endl;
return 0;
}
💾 Memory Management
🎯 Complete Definition (10 Lines)
Memory layout: Stack (automatic storage), heap (dynamic storage), static/global,
code segment. RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime.
Dynamic allocation: new operator allocates memory, returns pointer. delete frees memory.
new[]/delete[] for arrays. Placement new constructs object at pre-allocated memory.
Smart pointers (C++11): unique_ptr (exclusive ownership), shared_ptr (shared ownership
with reference counting), weak_ptr (non-owning reference to shared_ptr).
Move semantics (C++11): std::move transfers ownership, rvalue references (&&),
move constructors/assignment operators.
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Resource {
public:
Resource() { cout << "Resource acquired\n"; }
~Resource() { cout << "Resource released\n"; }
};
int main() {
// RAII example
{
Resource res; // Automatically destroyed when out of scope
}
// Smart pointers
auto ptr1 = make_shared();
{
auto ptr2 = ptr1; // Shared ownership
cout << "Use count: " << ptr1.use_count() << endl;
}
// Move semantics
vector v1 = {1, 2, 3};
vector v2 = move(v1); // v1 is now empty
cout << "v1 size: " << v1.size() << endl;
cout << "v2 size: " << v2.size() << endl;
return 0;
}
🛡️ Exceptions
🎯 Complete Definition (10 Lines)
Exceptions handle runtime errors. throw expression raises exception.
try block encloses code that might throw. catch blocks handle specific exceptions.
Exception hierarchy: std::exception base class, derived classes like
std::runtime_error, std::logic_error, std::bad_alloc. Custom exceptions should inherit from
std::exception.
Noexcept specifier (C++11): Indicates function won't throw. noexcept(expression)
checks if expression is non-throwing. Move operations should be noexcept.
Stack unwinding: Destructors called for automatic objects during stack unwinding.
#include <iostream>
#include <stdexcept>
using namespace std;
// Custom exception
class DivideByZero : public runtime_error {
public:
DivideByZero() : runtime_error("Division by zero!") {}
};
double divide(int a, int b) {
if(b == 0) throw DivideByZero();
return static_cast(a) / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(5, 0) << endl; // Throws
}
catch(const DivideByZero& e) {
cout << "Caught: " << e.what() << endl;
}
catch(const exception& e) {
cout << "Standard exception: " << e.what() << endl;
}
// noexcept example
void safeFunction() noexcept {
cout << "This won't throw\n";
}
safeFunction();
return 0;
}
📁 File Input/Output
🎯 Complete Definition (10 Lines)
File I/O via header: ifstream (input), ofstream (output), fstream (both).
Open modes: ios::in, ios::out, ios::app, ios::binary, ios::trunc.
Text files: << and >> operators, getline() for lines. Binary files: read() and write()
methods, seekg()/seekp() for positioning, tellg()/tellp() for position.
String streams: for in-memory string processing: istringstream (input),
ostringstream (output), stringstream (both).
Filesystem library (C++17): for directory operations, path manipulation,
file metadata.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
// Write to file
ofstream outFile("data.txt");
outFile << "C++ File I/O Example\n";
outFile << "Line 2\n";
outFile.close();
// Read from file
ifstream inFile("data.txt");
string line;
while(getline(inFile, line)) {
cout << "Read: " << line << endl;
}
inFile.close();
// String stream
string data = "John 25 95.5";
istringstream iss(data);
string name;
int age;
double score;
iss >> name >> age >> score;
cout << "Parsed: " << name << ", " << age << ", " << score << endl;
return 0;
}
🔥 Advanced C++
🎯 Complete Definition (10 Lines)
Modern C++ features: auto type deduction, range-based for loops, lambdas,
smart pointers, move semantics, constexpr functions, nullptr, override/final keywords.
C++17: Structured bindings, if/switch with initializer, std::optional,
std::variant, std::any, fold expressions, filesystem library, parallel algorithms.
C++20: Concepts, ranges, coroutines, modules, three-way comparison (<=>),
calendar/timezone, format library, std::span, constexpr virtual functions.
C++23: std::expected, std::mdspan, stacktraces, std::print, flat containers.
#include <iostream>
#include <vector>
#include <ranges> // C++20
#include <algorithm>
using namespace std;
// C++20 Concept
template
concept Numeric = is_arithmetic_v;
template
T square(T x) { return x * x; }
int main() {
// Range-based for with initializer (C++17)
if(vector nums = {1, 2, 3, 4, 5}; !nums.empty()) {
for(int n : nums) cout << n << " ";
cout << endl;
}
// Structured binding (C++17)
auto [min, max] = minmax({5, 3, 8, 1});
cout << "Min: " << min << ", Max: " << max << endl;
// C++20 Ranges
vector values = {5, 3, 8, 1, 9, 2};
auto even = values | views::filter([](int n) { return n % 2 == 0; });
cout << "Even numbers: ";
for(int n : even) cout << n << " ";
cout << endl;
return 0;
}