C++

Essential C++ syntax, data structures, and modern C++ features for system and application development.

languages
cppc++systemsprogrammingoop

Variables & Data Types

// Basic types
int number = 42;
double decimal = 3.14;
float pi = 3.14f;
char letter = 'A';
bool flag = true;

// Modern C++ auto keyword
auto value = 100;        // int
auto text = "hello";     // const char*

// Constants
const int MAX_SIZE = 100;
constexpr int COMPILE_TIME = 50;

// References and pointers
int x = 10;
int& ref = x;            // Reference
int* ptr = &x;           // Pointer
int* nullPtr = nullptr;  // Null pointer (C++11)

Strings

#include <string>

// String creation
std::string str = "Hello";
std::string str2("World");

// String operations
str.length();            // Get length
str.size();              // Same as length
str.empty();             // Check if empty
str += " World";         // Concatenation
str.append("!");         // Append
str.substr(0, 5);        // Substring
str.find("World");       // Find position
str.replace(0, 5, "Hi"); // Replace
str.c_str();             // Convert to C-string

Arrays & Vectors

#include <array>
#include <vector>

// C-style array
int arr[5] = {1, 2, 3, 4, 5};

// std::array (fixed size, C++11)
std::array<int, 5> stdArr = {1, 2, 3, 4, 5};

// std::vector (dynamic array)
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);        // Add element
vec.pop_back();          // Remove last
vec.size();              // Get size
vec.empty();             // Check if empty
vec.clear();             // Remove all elements
vec.at(0);               // Access with bounds check
vec[0];                  // Access without bounds check
vec.front();             // First element
vec.back();              // Last element

Control Flow

// If-else
if (condition) {
    // code
} else if (other) {
    // code
} else {
    // code
}

// Switch
switch (value) {
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
}

// Ternary operator
int result = (x > y) ? x : y;

Loops

// For loop
for (int i = 0; i < 10; i++) {
    // code
}

// Range-based for loop (C++11)
for (const auto& item : container) {
    // code
}

// While loop
while (condition) {
    // code
}

// Do-while loop
do {
    // code
} while (condition);

Functions

// Basic function
int add(int a, int b) {
    return a + b;
}

// Default parameters
void greet(std::string name = "World") {
    std::cout << "Hello, " << name << std::endl;
}

// Pass by reference
void modify(int& x) {
    x = x * 2;
}

// Pass by const reference (efficient for large objects)
void process(const std::vector<int>& data) {
    // read-only access
}

// Lambda functions (C++11)
auto add = [](int a, int b) { return a + b; };
auto addCapture = [x](int a) { return a + x; };  // Capture x
auto addRef = [&x](int a) { x += a; };           // Capture by reference

Classes & Objects

class Person {
private:
    std::string name;
    int age;

public:
    // Constructor
    Person(std::string n, int a) : name(n), age(a) {}

    // Default constructor
    Person() = default;

    // Destructor
    ~Person() {}

    // Member function
    void introduce() const {
        std::cout << "I'm " << name << std::endl;
    }

    // Getters and setters
    std::string getName() const { return name; }
    void setName(const std::string& n) { name = n; }
};

// Creating objects
Person p1("Alice", 30);
Person p2;                  // Default constructor
Person* p3 = new Person("Bob", 25);
delete p3;                  // Don't forget to delete!

Inheritance

class Animal {
public:
    virtual void speak() const {
        std::cout << "Animal sound" << std::endl;
    }
    virtual ~Animal() = default;  // Virtual destructor
};

class Dog : public Animal {
public:
    void speak() const override {
        std::cout << "Woof!" << std::endl;
    }
};

// Polymorphism
Animal* animal = new Dog();
animal->speak();  // Output: Woof!
delete animal;

Smart Pointers (C++11)

#include <memory>

// unique_ptr - exclusive ownership
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);

// shared_ptr - shared ownership
std::shared_ptr<int> ptr2 = std::make_shared<int>(42);
std::shared_ptr<int> ptr3 = ptr2;  // Reference count: 2

// weak_ptr - non-owning reference
std::weak_ptr<int> weak = ptr2;
if (auto shared = weak.lock()) {
    // Use shared safely
}

Containers

#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

// Map (ordered key-value pairs)
std::map<std::string, int> ages;
ages["Alice"] = 30;
ages.insert({"Bob", 25});
ages.find("Alice");          // Iterator to element
ages.count("Alice");         // 1 if exists, 0 otherwise

// Unordered map (hash table)
std::unordered_map<std::string, int> hashMap;

// Set (ordered unique elements)
std::set<int> uniqueNums = {3, 1, 4, 1, 5};

// Unordered set (hash set)
std::unordered_set<int> hashSet;

Templates

// Function template
template<typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

// Class template
template<typename T>
class Container {
private:
    T value;
public:
    Container(T v) : value(v) {}
    T getValue() const { return value; }
};

// Usage
int maxInt = maximum(5, 10);
Container<std::string> strContainer("Hello");

Exception Handling

#include <stdexcept>

try {
    if (error_condition) {
        throw std::runtime_error("Something went wrong");
    }
} catch (const std::runtime_error& e) {
    std::cerr << "Error: " << e.what() << std::endl;
} catch (const std::exception& e) {
    std::cerr << "Exception: " << e.what() << std::endl;
} catch (...) {
    std::cerr << "Unknown exception" << std::endl;
}

File I/O

#include <fstream>

// Writing to file
std::ofstream outFile("output.txt");
if (outFile.is_open()) {
    outFile << "Hello, File!" << std::endl;
    outFile.close();
}

// Reading from file
std::ifstream inFile("input.txt");
std::string line;
while (std::getline(inFile, line)) {
    std::cout << line << std::endl;
}
inFile.close();

Modern C++ Features

// Structured bindings (C++17)
std::pair<int, std::string> p = {1, "one"};
auto [num, str] = p;

// Optional (C++17)
#include <optional>
std::optional<int> maybeValue = std::nullopt;
if (maybeValue.has_value()) {
    int val = maybeValue.value();
}

// String view (C++17)
#include <string_view>
void process(std::string_view sv) {
    // Efficient, non-owning string reference
}

// Initializer lists
std::vector<int> nums = {1, 2, 3, 4, 5};

// nullptr instead of NULL
int* ptr = nullptr;

// Range-based algorithms (C++20)
#include <algorithm>
#include <ranges>
auto filtered = nums | std::views::filter([](int n) { return n > 2; });