README
Introduction to C++
Table of Contents
- •What is C++?
- •History of C++
- •Why Learn C++?
- •C++ Features
- •C++ vs Other Languages
- •Setting Up Your Environment
- •Your First C++ Program
- •The Compilation Process
- •Common Terminology
- •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++
| Year | Milestone |
|---|---|
| 1979 | Bjarne Stroustrup begins work on "C with Classes" |
| 1983 | Renamed to C++ |
| 1985 | First commercial release |
| 1998 | C++98 - First ISO standard |
| 2003 | C++03 - Bug fix release |
| 2011 | C++11 - Major modernization (auto, lambdas, smart pointers) |
| 2014 | C++14 - Refinements to C++11 |
| 2017 | C++17 - Filesystem, optional, variant |
| 2020 | C++20 - Concepts, ranges, coroutines, modules |
| 2023 | C++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
newanddelete - •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)
| Feature | Description |
|---|---|
auto | Automatic type deduction |
| Lambda expressions | Anonymous inline functions |
| Range-based for loops | Simplified iteration |
| Smart pointers | Automatic memory management |
| Move semantics | Efficient resource transfer |
nullptr | Type-safe null pointer |
constexpr | Compile-time computation |
| Structured bindings | Decompose objects easily |
C++ vs Other Languages
C++ vs C
| Aspect | C | C++ |
|---|---|---|
| Paradigm | Procedural | Multi-paradigm |
| OOP | No | Yes |
| Function Overloading | No | Yes |
| Standard Library | Minimal | Rich (STL) |
| Memory Safety | Manual | Manual + Smart Pointers |
C++ vs Java
| Aspect | C++ | Java |
|---|---|---|
| Compilation | To machine code | To bytecode (JVM) |
| Memory | Manual + Smart Pointers | Garbage Collection |
| Performance | Generally faster | Slower startup |
| Pointers | Yes | No (references only) |
| Multiple Inheritance | Yes | Interfaces only |
C++ vs Python
| Aspect | C++ | Python |
|---|---|---|
| Typing | Static | Dynamic |
| Speed | Very fast | Slower |
| Syntax | Complex | Simple |
| Use Case | Systems, performance | Scripting, ML, web |
| Learning Curve | Steep | Gentle |
C++ vs Rust
| Aspect | C++ | Rust |
|---|---|---|
| Memory Safety | Manual responsibility | Compiler enforced |
| Null Pointers | Possible | Option types |
| Concurrency | Threads + locks | Ownership system |
| Legacy Code | Massive ecosystem | Growing 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
- •Install MinGW-w64 or use WSL (Windows Subsystem for Linux)
- •Download from: https://www.mingw-w64.org/
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
| Tool | Platform | Features |
|---|---|---|
| VS Code | All | Lightweight, extensions |
| CLion | All | Full IDE, CMake integration |
| Visual Studio | Windows | Powerful debugger |
| Qt Creator | All | Good for Qt projects |
| Vim/Neovim | All | Terminal-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>
- •
#includetells 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 - •
intmeans main returns an integer - •
return 0signals 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
| Flag | Purpose |
|---|---|
-std=c++17 | Use C++17 standard |
-Wall | Enable common warnings |
-Wextra | Enable extra warnings |
-o program | Name output file "program" |
-g | Include debug information |
-O2 | Optimization 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
#includedirectives (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
| Term | Definition |
|---|---|
| Source Code | Human-readable program text (.cpp files) |
| Header File | Contains declarations (.h or .hpp files) |
| Object File | Compiled binary code (.o or .obj files) |
| Executable | Final runnable program |
| Compiler | Translates source code to machine code |
| Linker | Combines object files into executable |
| IDE | Integrated Development Environment |
| Debugger | Tool for finding and fixing bugs |
C++ Specific Terms
| Term | Definition |
|---|---|
| Namespace | Container for identifiers to avoid conflicts |
| Class | Blueprint for creating objects |
| Object | Instance of a class |
| Method | Function belonging to a class |
| Template | Generic programming construct |
| STL | Standard Template Library |
| RAII | Resource Acquisition Is Initialization |
| Scope | Region where a variable is accessible |
Memory Terms
| Term | Definition |
|---|---|
| Stack | Fast memory for local variables |
| Heap | Dynamic memory for runtime allocation |
| Pointer | Variable storing memory address |
| Reference | Alias for another variable |
| Memory Leak | Allocated 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
- •Write minimal code first
- •Test it works
- •Add one feature
- •Test again
- •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
- •✅ Set up your development environment
- •✅ Write and compile "Hello, World!"
- •📖 Move on to Syntax and Structure lesson
- •💻 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