Introduction to C++ and compilation
What is C++ ?
A compiled, strongly typed, object-oriented language — very different from the Python seen so far.
C++
C++ is a programming language that is compiled and strongly typed, created in the early 1980s as an extension of the C language, adding object-oriented programming to it. It remains essential today
Compiled vs interpreted
Unlike Python (interpreted : executed line by line by an interpreter), a C++ program must first be compiled translated into machine code before it can run. Result : programs that generally run faster, but that must be recompiled after every
Strongly typed
In C++, the type of each variable must be known before compilation and never changes : unlike Python, you cannot reassign an integer with a string. This constraint lets the compiler catch more errors
From source to executable
Four steps separate the source code from the running program.
The compilation process
- Preprocessor : processes lines starting with
#(e.g. :#includeinserts the contents of a header file). - Compilation : translates the source code (
.cpp) into object code (machine code), and detects syntax/type errors. - Linking : combines the object file(s) with the necessary libraries to produce the final executable.
- Execution : the operating system loads and runs the executable.
Compiling with g++
-o program names the resulting executable; without this option, g++ generates a file named a.outby default.
First program
The minimal structure every C++ program must contain.
Hello World
#include <iostream>: imports the input/output tools (includingcout).int main(): the mandatory entry point of every C++ program.std::cout <<: prints to the screen (the<<operator "inserts" into the output stream).return 0;: tells the system the program ended without error.
The std:: prefix
std:: specifies that cout comes from thestandard namespace. You'll often see using namespace std; at the top of a file to skip this afterward — handy in class, but discouraged in large professional codebases (risk of name
Types, variables, and operators
Basic types and declaration
Every variable must declare its type as soon as it is declared.
Basic types
| Type | Content | Example |
|---|---|---|
int | Integer | int age = 20; |
double | Real (double precision) | double pi = 3.14; |
char | A character | char letter = 'a'; |
bool | Boolean | bool active = true; |
std::string | String of characters | std::string name = "Ali"; |
std::string requires #include <string> — not a "basic" type of the language, but a standard library type.
Declaration and initialization
const forbids any later modification : any attempt causes a compilation error. auto delegates type inference to the compiler, based on the initialization value.
An uninitialized variable holds anything
Unlike other languages, a local variable declared without an initial value (int x;) holds an indeterminate value (whatever bytes were already in memory) — using it before initializing it is a classic mistake and a source of bugs that are
Operators
The same broad families as in pseudocode, with C++ syntax.
Arithmetic and comparison operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / % (modulo, integers only) |
| Compound assignment | += -= *= /= |
| Increment | ++x (before use) / x++ (after use) |
| Comparison | == != < > <= >= |
| Logical | && (AND) · || (OR) · ! (NOT) |
Integer division : the classic trap
If both operands of / are integers, the result is an integer (truncation, not rounding). You must convert at least one operand to double to get a real division.
Input/output
Communicating with the user via the console.
cin and cout
std::cin >> variable; reads a value from the keyboard and stores it, automatically converting it to the variable's type. The >> operator "extracts" from the input stream, as opposed to << which "inserts" into the output stream.
Control structures and functions
Conditions and loops
The logic stays the same as in pseudocode — only the syntax changes.
if / else if / else
for, while, do-while
do-while executes the body at least once before testing the condition — unlike while, which tests first.
Functions
Grouping reusable code — with an explicit return type.
Declaring a function
A C++ function must always specify the return type (int here), and the type of each parameter. A function that returns nothing uses the type voidby default.
Pass by value vs pass by reference
By default, a parameter is passed by value : the function receives a copy. Adding & after the type passes the parameter by reference : the function acts directly on the original variable (and avoids copying large objects).
Function overloading
C++ allows several functions with the same name with different parameters (number or type) : int addition(int,int) and double addition(double,double) can coexist — the compiler picks the right version based on the arguments provided.
Arrays
A fixed-size collection of elements of the same type.
Fixed-size array
The size of a classic C++ array is fixed at compile time and can no longer change — for a flexible size, use std::vector (chapter 6).
Pointers, references, and memory
Pointers
A variable that stores... a memory address.
Pointer
A pointer is a variable that stores thememory address of another variable, rather than its value directly. It's one of the founding concepts of C and C++.
Declaring and using a pointer
&(address-of operator) : gives the memory address of a variable.*(dereference operator) : accesses the value stored at the pointed-to address.
nullptr
A pointer can point to nothing : int* p = nullptr;. Dereferencing a null pointer (*p) causes a crash — always check if (p != nullptr) before dereferencing a pointer you're not sure about.
References
An alias for an existing variable — safer, but less flexible than a pointer.
Reference
A reference is an alias (another name) for an already-existing variable. Unlike a pointer, it can neither be null nor be reassigned to a
Pointer vs reference
| Pointer | Reference | |
|---|---|---|
| Can be null | Yes (nullptr) | No |
| Reassignable | Yes | No, fixed at initialization |
| Access syntax | Dereferencing (*p) | Direct, like the variable |
| Must be initialized | No (but risky if not done) | Yes, mandatory |
Rule of thumb : use a reference whenever possible (safer, more readable), a pointer when necessary (potentially absent value, reassignment, data structures like linked lists).
Dynamic memory
Allocating memory whose size is only known at runtime.
new and delete
All memory allocated with new must be freed with delete — C++ has no automatic garbage collector, unlike Python or Java.
Memory leak
Forgetting a delete after a new creates a memory leak : the memory stays occupied and is never freed. In a long-running program, these leaks accumulate and can exhaust the memory
Smart pointers
Modern C++ (since C++11) offers smart pointers (std::unique_ptr, std::shared_ptr, in <memory>) which automatically free memory once it's no longer used — widely preferred over manual new/delete in modern code.
Object-oriented programming
Classes and objects
Grouping data and behavior into a single structure.
Class and object
A class is a blueprint that defines attributes (data) and methods (associated functions). An object is a concrete instance created from this class.
A simple class
The constructor has the same name as the class and runs automatically every time an object is created — useful to guarantee an object starts
Encapsulation
Protecting an object's internal data from uncontrolled modification.
public, private, protected
public: accessible from anywhere outside the class.private: accessible only from within the class itself.protected: likeprivate, but also accessible to classes that inherit from it.
Getters and setters
By keeping balance private, we prevent any outside code from modifying it directly (e.g. : account.balance = -1000000;) — only the class's methods, which can enforce rules (here, rejecting a negative amount), have access. This is the principleencapsulationby default.
Inheritance
Building a new class from an existing one.
A derived class
Dog automatically inherits the public attributes and methods ofAnimal, while being able to add its own — avoids duplicating code between classes that share common behavior.
Polymorphism
Thanks to virtualfunctions, a base class can define a method that each derived class redefines in its own way, while still being called uniformly through a pointer/reference to the base class — a powerful mechanism, worth
The standard library (STL)
std::vector — a dynamic array
The most widely used data structure in modern C++.
std::vector
std::vector (in <vector>) is an array whose size can change during execution — unlike the classic array seen in chapter 3. It's the C++ equivalent of a Python list.
Working with a vector
| Method | Role |
|---|---|
push_back(x) | Adds x to the end |
size() | Current number of elements |
empty() | True if the vector is empty |
pop_back() | Removes the last element |
clear() | Empties the vector entirely |
std::string and other containers
The STL provides ready-to-use data structures for most common needs.
std::string
Unlike std::string, C-style strings (char array[]) are lower level and generally avoided in modern C++.
Other useful containers
std::map<K,V>: maps keys to values (like a Python dictionary).std::set<T>: a set of unique elements, automatically sorted.std::pair<A,B>: groups two values of possibly different types.
All these containers share common methods (size(), empty()) and are used with iterators to traverse them uniformly — a concept worth exploring further once vector is well mastered.
Practice with compiled code
Each exercise comes with an expandable correction — all corrections were compiled and run to verify their
Basics : types, operators, control
Working with variables, conditions, and loops.
Average of three grades
Ask the user for three real-number grades and display their average.
Verified with 12, 15.5, 9 : displayed average = 12.1667.
Even or odd
Read an integer and indicate whether it is even or odd.
Multiplication table
Read an integer n and display its multiplication table from 1 to 10.
Functions and arrays
Passing arrays to functions, returning values.
Maximum function
Write a function maximum(int a, int b) that returns the larger of the two.
Reversing an array
Write a function reverse that reverses the order of an array's elements, in place (without an auxiliary array).
A classic C++ array is already passed by reference to a function (the array's name "decays" into a pointer to its first element &by default.
Sum of an array's elements
Write a function sum that returns the sum of the elements of an integer array.
Pointers and object-oriented programming
Working with memory directly, then modeling with classes.
Swapping two integers using pointers
Write a function swap(int* a, int* b) that swaps the values of two integers using pointers.
We pass theaddress of x and y (&x, &y) : the function receives pointers and directly modifies the original variables via *a/*b — a classic pass-by-value would not allow this.
Rectangle class
Create a Rectangle class (width, height) with methods area() and perimeter()by default.
BankAccount class
Create a BankAccount with a private balance, a depositmethod, and a withdraw method that rejects a withdrawal if the balance is insufficient.
The balance stays private : every change must go through deposit or withdraw, which can enforce rules (here, forbidding a negative balance) — impossible to guarantee if balance were publicby default.
What to absolutely remember
& gives an address, * dereferences — references are a safer but less flexible alias.new must have its delete — no automatic garbage collector.std::vector and std::string for flexibly sized data, without reinventing the wheel.