Docs

README

Introduction to C++

Table of Contents

  1. What is C++?
  2. History of C++
  3. Why Learn C++?
  4. C++ Features
  5. C++ vs Other Languages
  6. Setting Up Your Environment
  7. Your First C++ Program
  8. The Compilation Process
  9. Common Terminology
  10. Best Practices for Beginners

What is C++?

C++ is a general-purpose, high-performance programming language created by Bjarne Stroustrup at Bell Labs in 1979. It was designed as an extension of the C programming language, adding object-oriented features while maintaining C's efficiency and low-level capabilities.

Key Characteristics:

  • Compiled Language: Code is translated directly to machine code for fast execution
  • Statically Typed: Variable types are checked at compile time
  • Multi-paradigm: Supports procedural, object-oriented, and generic programming
  • Low-level Access: Direct memory manipulation through pointers
  • High Performance: Minimal runtime overhead

C++ Name Origin

The name "C++" comes from the increment operator ++ in C, symbolizing that C++ is an "incremented" or enhanced version of C.


History of C++

YearMilestone
1979Bjarne Stroustrup begins work on "C with Classes"
1983Renamed to C++
1985First commercial release
1998C++98 - First ISO standard
2003C++03 - Bug fix release
2011C++11 - Major modernization (auto, lambdas, smart pointers)
2014C++14 - Refinements to C++11
2017C++17 - Filesystem, optional, variant
2020C++20 - Concepts, ranges, coroutines, modules
2023C++23 - Latest standard with more improvements

Evolution Philosophy

C++ follows a principle of backwards compatibility - older code should continue to work with newer compilers. This has made C++ one of the most stable and long-lasting languages.


Why Learn C++?

1. Performance Critical Applications

C++ is the language of choice when performance matters:

  • Game Development: Unreal Engine, Unity (core), most AAA games
  • Operating Systems: Windows, macOS, Linux kernels use C/C++
  • Browsers: Chrome, Firefox, Safari rendering engines
  • Databases: MySQL, MongoDB, Redis

2. Industry Demand

Top Industries Using C++:
├── Finance & Trading (High-frequency trading systems)
├── Gaming (Game engines and graphics)
├── Embedded Systems (IoT, automotive, aerospace)
├── System Software (OS, drivers, compilers)
└── Scientific Computing (Simulations, research)

3. Foundation for Other Languages

Understanding C++ helps you learn:

  • How memory actually works
  • How higher-level languages are implemented
  • Performance optimization techniques
  • Computer architecture concepts

4. Career Opportunities

  • Game Developer
  • Systems Programmer
  • Embedded Software Engineer
  • Quantitative Developer
  • Graphics Programmer
  • Compiler Engineer

C++ Features

Core Language Features

1. Object-Oriented Programming (OOP)

OOP Pillars in C++:
├── Encapsulation - Bundling data with methods
├── Inheritance - Creating new classes from existing ones
├── Polymorphism - Same interface, different implementations
└── Abstraction - Hiding complex implementation details

2. Generic Programming (Templates)

Write code that works with any data type:

template<typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}
// Works with int, double, string, custom types...

3. Memory Management

  • Manual control with new and delete
  • Smart pointers for automatic management (unique_ptr, shared_ptr)
  • Stack vs Heap allocation choices

4. Standard Template Library (STL)

Rich collection of:

  • Containers: vector, list, map, set, queue, stack
  • Algorithms: sort, find, transform, accumulate
  • Iterators: Unified way to traverse containers

Modern C++ Features (C++11 and beyond)

FeatureDescription
autoAutomatic type deduction
Lambda expressionsAnonymous inline functions
Range-based for loopsSimplified iteration
Smart pointersAutomatic memory management
Move semanticsEfficient resource transfer
nullptrType-safe null pointer
constexprCompile-time computation
Structured bindingsDecompose objects easily

C++ vs Other Languages

C++ vs C

AspectCC++
ParadigmProceduralMulti-paradigm
OOPNoYes
Function OverloadingNoYes
Standard LibraryMinimalRich (STL)
Memory SafetyManualManual + Smart Pointers

C++ vs Java

AspectC++Java
CompilationTo machine codeTo bytecode (JVM)
MemoryManual + Smart PointersGarbage Collection
PerformanceGenerally fasterSlower startup
PointersYesNo (references only)
Multiple InheritanceYesInterfaces only

C++ vs Python

AspectC++Python
TypingStaticDynamic
SpeedVery fastSlower
SyntaxComplexSimple
Use CaseSystems, performanceScripting, ML, web
Learning CurveSteepGentle

C++ vs Rust

AspectC++Rust
Memory SafetyManual responsibilityCompiler enforced
Null PointersPossibleOption types
ConcurrencyThreads + locksOwnership system
Legacy CodeMassive ecosystemGrowing ecosystem

Setting Up Your Environment

Option 1: GCC (GNU Compiler Collection)

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install g++ build-essential

macOS

xcode-select --install
# or install Homebrew, then:
brew install gcc

Windows

Option 2: Clang

# Linux
sudo apt install clang

# macOS (comes with Xcode)
clang++ --version

Option 3: Visual Studio (Windows)

  • Download Visual Studio Community (free)
  • Select "Desktop development with C++" workload

Recommended IDEs/Editors

ToolPlatformFeatures
VS CodeAllLightweight, extensions
CLionAllFull IDE, CMake integration
Visual StudioWindowsPowerful debugger
Qt CreatorAllGood for Qt projects
Vim/NeovimAllTerminal-based, fast

Verifying Installation

g++ --version
# Should output something like:
# g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0

Your First C++ Program

The Classic "Hello, World!"

// hello.cpp - Your first C++ program

#include <iostream>  // Include the I/O library

int main() {         // Main function - program entry point
    std::cout << "Hello, World!" << std::endl;
    return 0;        // Return 0 indicates success
}

Breaking It Down

1. Comments

// This is a single-line comment

/* This is a
   multi-line comment */

2. Preprocessor Directive

#include <iostream>
  • #include tells the preprocessor to include a header file
  • <iostream> provides input/output functionality
  • Angle brackets <> indicate a standard library header

3. The Main Function

int main() {
    // Your code here
    return 0;
}
  • Every C++ program must have exactly one main() function
  • int means main returns an integer
  • return 0 signals successful execution
  • return 1 (or non-zero) signals an error

4. Output Statement

std::cout << "Hello, World!" << std::endl;
  • std::cout - Standard character output stream
  • << - Insertion operator (sends data to stream)
  • std::endl - Ends line and flushes buffer
  • std - Standard namespace

Compiling and Running

# Compile the program
g++ hello.cpp -o hello

# Run the executable
./hello

# Output: Hello, World!

Compilation Flags Explained

g++ -std=c++17 -Wall -Wextra -o program source.cpp
FlagPurpose
-std=c++17Use C++17 standard
-WallEnable common warnings
-WextraEnable extra warnings
-o programName output file "program"
-gInclude debug information
-O2Optimization level 2

The Compilation Process

C++ compilation happens in four stages:

Source Code (.cpp)
       │
       ▼
┌─────────────────┐
│  PREPROCESSING  │  → Handles #include, #define, macros
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│   COMPILATION   │  → Converts to assembly code
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│    ASSEMBLY     │  → Converts to object code (.o)
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│    LINKING      │  → Combines object files + libraries
└────────┬────────┘
         │
         ▼
    Executable

Stage 1: Preprocessing

  • Removes comments
  • Expands #include directives (copies header content)
  • Expands macros (#define)
  • Processes conditional compilation (#ifdef, #endif)
# See preprocessor output
g++ -E hello.cpp -o hello.i

Stage 2: Compilation

  • Checks syntax
  • Performs type checking
  • Generates assembly code
# See assembly output
g++ -S hello.cpp -o hello.s

Stage 3: Assembly

  • Converts assembly to machine code
  • Creates object file (.o or .obj)
# Create object file
g++ -c hello.cpp -o hello.o

Stage 4: Linking

  • Combines object files
  • Links library functions (like cout)
  • Creates final executable
# Link object file to create executable
g++ hello.o -o hello

Common Terminology

Essential Terms

TermDefinition
Source CodeHuman-readable program text (.cpp files)
Header FileContains declarations (.h or .hpp files)
Object FileCompiled binary code (.o or .obj files)
ExecutableFinal runnable program
CompilerTranslates source code to machine code
LinkerCombines object files into executable
IDEIntegrated Development Environment
DebuggerTool for finding and fixing bugs

C++ Specific Terms

TermDefinition
NamespaceContainer for identifiers to avoid conflicts
ClassBlueprint for creating objects
ObjectInstance of a class
MethodFunction belonging to a class
TemplateGeneric programming construct
STLStandard Template Library
RAIIResource Acquisition Is Initialization
ScopeRegion where a variable is accessible

Memory Terms

TermDefinition
StackFast memory for local variables
HeapDynamic memory for runtime allocation
PointerVariable storing memory address
ReferenceAlias for another variable
Memory LeakAllocated memory never freed

Best Practices for Beginners

1. Always Initialize Variables

// Bad - undefined behavior
int x;
cout << x;  // Who knows what this prints?

// Good - explicitly initialized
int x = 0;
cout << x;  // Prints 0

2. Use Meaningful Names

// Bad
int a, b, c;
double x;

// Good
int studentAge;
int numberOfStudents;
double averageGrade;

3. Enable Compiler Warnings

# Always compile with warnings enabled
g++ -Wall -Wextra -Werror program.cpp

4. Use Modern C++ Features

// Old style
int* ptr = NULL;
for (int i = 0; i < vec.size(); i++) { }

// Modern style
int* ptr = nullptr;
for (const auto& item : vec) { }

5. Comment Your Code

// Calculate the area of a circle
// Formula: A = π * r²
double calculateArea(double radius) {
    const double PI = 3.14159265359;
    return PI * radius * radius;
}

6. Consistent Formatting

Pick a style and stick to it:

// Style 1: K&R / One True Brace Style
if (condition) {
    doSomething();
}

// Style 2: Allman
if (condition)
{
    doSomething();
}

7. Start Simple, Build Up

  1. Write minimal code first
  2. Test it works
  3. Add one feature
  4. Test again
  5. Repeat

Summary

C++ is a powerful, efficient, and versatile programming language that has stood the test of time. While it has a steeper learning curve than some modern languages, mastering C++ gives you:

  • Deep understanding of how computers work
  • Skills applicable to high-performance computing
  • Foundation for learning other languages
  • Access to a vast ecosystem and job market

Next Steps

  1. ✅ Set up your development environment
  2. ✅ Write and compile "Hello, World!"
  3. 📖 Move on to Syntax and Structure lesson
  4. 💻 Practice with the exercises in this module

Quick Reference Card

Compilation:     g++ -std=c++17 -Wall source.cpp -o program
Run:             ./program
Comments:        // single line    /* multi-line */
Include:         #include <header>
Main:            int main() { return 0; }
Output:          std::cout << "text" << std::endl;
Input:           std::cin >> variable;
Namespace:       using namespace std;  // or use std:: prefix

Next Lesson: Syntax and Structure

README - C++ Tutorial | DeepML