Getting Started
C++ is a powerful, high-performance language that serves as the backbone for game engines, operating systems, and high-frequency trading applications. It gives you **direct control over system resources** and memory, which is why understanding the compilation process is key.
#include <iostream> // Prefer <iostream> over <bits/stdc++.h> for standard practice
using namespace std;
int main() {
cout << "Hello, Developer HUB!" << endl; // Use endl for flushing output
return 0; // Standard practice for success
}
- Understand **
compile → link → run**: Your source code is compiled into machine code, linked with necessary libraries, and then executed. - Use **
g++ -std=c++17 -O2 main.cpp -o app**: This command compiles `main.cpp`, enables C++17 features, applies optimization level 2, and names the output executable `app`.
OOP Essentials
Object-Oriented Programming (OOP) in C++ revolves around the concepts of **Classes and Objects**. A class is a blueprint, and an object is an instance of that blueprint.
class User { // Prefer 'class' for OOP constructs
private:
string name;
int age;
public:
// Constructor
User(string n, int a) : name(n), age(a) {}
// Public Method
void greet() const {
cout << "Hi " << name << ", you are " << age << " years old.\n";
}
// Accessor (Getter)
string getName() const { return name; }
};
// Usage: User developer("Muaaz", 25); developer.greet();
- **Encapsulation**: Bundling data (`name`, `age`) and methods (`greet`) that operate on the data into a single unit (the class). Use `private` and `public` access specifiers.
- **Inheritance**: A mechanism where one class acquires the properties and methods of another.
- **Polymorphism**: The ability of a function or method to take on multiple forms (often achieved through virtual functions and function overloading).
Pointers and Memory Management
C++ offers **manual memory control**, a key feature that contributes to its performance. This involves understanding the **Stack** (for local variables) and the **Heap** (for dynamically allocated memory).
int value = 42; int* ptr = &value; // Pointer stores the memory address of 'value' *ptr = 100; // Dereferencing: changes the value at the address // Dynamic memory: must be explicitly deallocated int* dynamic_val = new int(50); // ... use dynamic_val ... delete dynamic_val; // FREE the allocated memory dynamic_val = nullptr; // Good practice to avoid dangling pointers
- **Pointers (`*`)**: Variables that store memory addresses. Essential for working with arrays, dynamic memory, and optimizing function calls.
- **References (`&`)**: Aliases for existing variables. They must be initialized and cannot be reassigned. Often used for function parameters to avoid costly copying.
- **Smart Pointers**: Modern C++ (C++11 and later) introduced `std::unique_ptr` and `std::shared_ptr` to manage heap memory automatically, significantly reducing memory leaks.
The Standard Template Library (STL)
The STL is a massive collection of pre-written components (templates) that dramatically speed up development. It is organized into three main categories: **Containers, Algorithms, and Iterators**.
Containers 📦
Containers are objects that store data. They manage the memory allocated to the objects they hold.
#include <vector>
#include <map>
std::vector<int> numbers = {10, 20, 30}; // Dynamic array
numbers.push_back(40);
std::map<std::string, int> ages; // Key-value pairs (sorted)
ages["Alice"] = 30;
- **Sequential**: `vector` (resizable array), `list` (doubly-linked list), `deque`.
- **Associative**: `map` (sorted key-value), `set` (sorted unique elements), `unordered_map`/`unordered_set` (hash-based, faster average access).
- **Container Adapters**: `stack`, `queue`, `priority_queue`.
Algorithms ⚙️
Algorithms process the data stored in containers. They are generic and work with any container type.
#include <algorithm> #include <numeric> std::sort(numbers.begin(), numbers.end()); // Sorts the vector int sum = std::accumulate(numbers.begin(), numbers.end(), 0); // Calculates the sum
- **Searching and Sorting**: `std::find`, `std::sort`, `std::binary_search`.
- **Manipulating**: `std::transform`, `std::reverse`, `std::copy`.
Iterators 🧭
Iterators act like pointers, allowing traversal through the elements of a container.
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
// Modern range-based for loop (uses iterators behind the scenes)
for (int num : numbers) {
cout << num << " ";
}
Modern C++: Key Features
C++ has evolved significantly with C++11, C++14, C++17, and C++20, adding features to make it safer, faster, and easier to write.
- **Lambda Functions**: Anonymous functions that can be defined inline. Perfect for short operations passed to algorithms like `std::sort`.
- **`auto` Keyword**: Allows the compiler to automatically deduce the type of a variable, reducing boilerplate code (e.g., `auto num = 42;`).
- **Concurrency (`<thread>`)**: Built-in support for multithreading, allowing you to run multiple tasks simultaneously.
- **Concepts (C++20)**: Improve template programming by letting you specify requirements on template parameters, resulting in much cleaner error messages.