C++ in Action: A Modern Collection of Code Examples and Solutions

Written by

in

The Ultimate Collection of C++ Examples: From Basics to Advanced

To give you the most practical and immediate value, this article focuses on a modern, standard console application environment using C++20. This allows us to explore clean syntax and powerful features without getting bogged down in platform-specific GUI code. 1. The Basics: Fundamentals of C++

Every master was once a beginner. These foundational examples establish the core syntax, control flow, and data handling structures of C++. Hello World

The traditional starting point demonstrates basic output and header inclusion.

#include int main() { std::cout << “Hello, World!” << std::endl; return 0; } Use code with caution. Variables and User Input

This script shows how to declare different data types and accept input from the console.

#include #include int main() { std::string name; int age = 0; std::cout << “Enter your name: “; std::getline(std::cin, name); std::cout << “Enter your age: “; std::cin >> age; std::cout << “Hello ” << name << “, you are ” << age << “ years old. “; return 0; } Use code with caution. Control Flow (If/Else and Loops)

Manage the execution path of your program using conditional logic and loops.

#include int main() { int number = 10; // Conditional if (number % 2 == 0) { std::cout << number << ” is even. “; } else { std::cout << number << ” is odd. “; } // For loop std::cout << “Counting to 5: “; for (int i = 1; i <= 5; ++i) { std::cout << i << ” “; } std::cout << ” “; return 0; } Use code with caution. 2. Intermediate: Functions, Pointers, and Arrays

Move beyond sequential code by organizing your logic into reusable blocks, managing memory address structures, and storing collections of data. Functions and Reference Passing

Passing parameters by reference avoids expensive data copying and allows a function to modify the original variable.

#include // Pass by reference allows modifying the original values void swap(int& a, int& b) { int temp = a; a = b; b = temp; } int main() { int x = 5, y = 10; swap(x, y); std::cout << “x: ” << x << “, y: ” << y << “ “; // Outputs: x: 10, y: 5 return 0; } Use code with caution. Pointers and Memory Addresses

Pointers hold the memory addresses of other variables, forming the bedrock of C++ memory management.

#include int main() { int variable = 42; intpointer = &variable; // Store address std::cout << “Value: ” << variable << “ “; std::cout << “Memory Address: ” << pointer << “ “; std::cout << “Value via Pointer: ” << pointer << “ “; // Dereferencing return 0; } Use code with caution. Dynamic Arrays with std::vector

Avoid rigid C-style arrays. The Standard Template Library (STL) vector handles dynamic resizing automatically.

#include #include int main() { std::vector numbers = {1, 2, 3}; numbers.push_back(4); // Dynamically adds element for (int num : numbers) { std::cout << num << ” “; } std::cout << ” “; return 0; } Use code with caution. 3. Advanced: Object-Oriented Programming (OOP)

C++ is highly regarded for its robust OOP capabilities. These concepts allow you to model real-world systems cleanly. Classes and Objects Encapsulate data and behaviors into distinct classes. Use code with caution. Inheritance and Polymorphism

Use virtual functions to create a unified interface for varying derived class behaviors.

#include #include class Shape { public: virtual void draw() const = 0; // Pure virtual function virtual ~Shape() = default; // Virtual destructor }; class Circle : public Shape { public: void draw() const override { std::cout << “Drawing a Circle. “; } }; class Square : public Shape { public: void draw() const override { std::cout << “Drawing a Square. “; } }; int main() { std::vector> shapes; shapes.push_back(new Circle()); shapes.push_back(new Square()); for (const auto& shape : shapes) { shape->draw(); // Dynamic binding } // Clean up memory for (auto& shape : shapes) { delete shape; } return 0; } Use code with caution. 4. Expert: Templates, Smart Pointers, and Modern Features

Modern C++ focuses on type safety, speed, and automated resource management. Templates (Generic Programming)

Write code once and let the compiler generate types dynamically.

#include template T findMax(T a, T b) { return (a > b) ? a : b; } int main() { std::cout << findMax(10, 20) << ” “; std::cout << findMax(5.5, 2.1) << ” “; return 0; } Use code with caution. Smart Pointers (std::unique_ptr)

Eliminate explicit delete keywords and prevent memory leaks using automatic scoping tools.

#include #include class Resource { public: Resource() { std::cout << “Resource acquired. “; } ~Resource() { std::cout << “Resource destroyed automatically. “; } void doWork() { std::cout << “Working… “; } }; int main() { { std::unique_ptr resPtr = std::make_unique(); resPtr->doWork(); } // resPtr goes out of scope here, memory is automatically freed std::cout << “Scope ended. “; return 0; } Use code with caution. Modern C++20 Concepts

Enforce template arguments to meet specific criteria at compile-time for cleaner error logs.

#include #include // This function only accepts integral types (int, long, char, etc.) template requires std::integral T add(T a, T b) { return a + b; } int main() { std::cout << add(5, 10) << ” “; // Works fine // std::cout << add(5.5, 2.3); // Compile error: double is not an integral type return 0; } Use code with caution.

To help refine this collection or take it to the next level, tell me:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *