Revision sheet

Programming
C++.

Level : Beginner

From compilation to pointers, through object-oriented programming and the standard library (STL) — the foundations

Each hands-on lab comes with an expandable correction — compiled and verified code.

Filter cards
All
Definition
Syntax
Example
Remark
Exercise
Key takeaways
Chapter 1

Introduction to C++ and compilation

Section 1.1

What is C++ ?

A compiled, strongly typed, object-oriented language — very different from the Python seen so far.

Definition

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

Remark

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

Remark

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

Section 1.2

From source to executable

Four steps separate the source code from the running program.

Steps

The compilation process

  1. Preprocessor : processes lines starting with # (e.g. : #include inserts the contents of a header file).
  2. Compilation : translates the source code (.cpp) into object code (machine code), and detects syntax/type errors.
  3. Linking : combines the object file(s) with the necessary libraries to produce the final executable.
  4. Execution : the operating system loads and runs the executable.
Syntax

Compiling with g++

g++ program.cpp -o program ./program

-o program names the resulting executable; without this option, g++ generates a file named a.outby default.

Section 1.3

First program

The minimal structure every C++ program must contain.

Syntax

Hello World

#include <iostream> int main() { std::cout << "Hello, world!" << std::endl; return 0; }
  • #include <iostream> : imports the input/output tools (including cout).
  • 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.
Remark

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

Chapter 2

Types, variables, and operators

Section 2.1 – 2.2

Basic types and declaration

Every variable must declare its type as soon as it is declared.

Formula

Basic types

TypeContentExample
intIntegerint age = 20;
doubleReal (double precision)double pi = 3.14;
charA characterchar letter = 'a';
boolBooleanbool active = true;
std::stringString of charactersstd::string name = "Ali";

std::string requires #include <string> — not a "basic" type of the language, but a standard library type.

Syntax

Declaration and initialization

int x; // declared, indeterminate value int y = 5; // declared and initialized const int N = 10; // constant: fixed value auto z = 3.14; // the compiler infers the type (double)

const forbids any later modification : any attempt causes a compilation error. auto delegates type inference to the compiler, based on the initialization value.

Remark

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

Section 2.3

Operators

The same broad families as in pseudocode, with C++ syntax.

Formula

Arithmetic and comparison operators

CategoryOperators
Arithmetic+ - * / % (modulo, integers only)
Compound assignment+= -= *= /=
Increment++x (before use) / x++ (after use)
Comparison== != < > <= >=
Logical&& (AND) · || (OR) · ! (NOT)
Careful

Integer division : the classic trap

int a = 7, b = 2; std::cout << a / b; // prints 3, not 3.5 ! std::cout << (double)a / b; // prints 3.5

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.

Section 2.4

Input/output

Communicating with the user via the console.

Syntax

cin and cout

#include <iostream> int main() { int age; std::cout << "How old are you? "; std::cin >> age; std::cout << "Yo

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.

Chapter 3

Control structures and functions

Section 3.1

Conditions and loops

The logic stays the same as in pseudocode — only the syntax changes.

Syntax

if / else if / else

if (grade >= 10) { std::cout << "Pass"; } else if (grade >= 8) { std::cout << "Resit"; } else { std::cout << "Fail
Syntax

for, while, do-while

for (int i = 0; i < 5; i++) { std::cout << i << " "; } int i = 0; while (i < 5) { std::cout << i << " "; i++; } int

do-while executes the body at least once before testing the condition — unlike while, which tests first.

Section 3.3

Functions

Grouping reusable code — with an explicit return type.

Syntax

Declaring a function

int addition(int a, int b) { return a + b; } int main() { int result = addition(3, 4); std::cout << result; // 7 return 0; }

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.

Syntax

Pass by value vs pass by reference

void byValue(int x) { x = x * 2; // only modifies the local copy } void byReference(int& x) { x = x * 2; // directly modifies the original variable }

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).

Remark

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.

Section 3.4

Arrays

A fixed-size collection of elements of the same type.

Syntax

Fixed-size array

int grades[5] = {12, 15, 8, 17, 10}; std::cout << grades[0]; // 12 (indexing starts at 0) for (int i = 0; i < 5; i++) { std::cout << grades[i] << " "; }

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).

Chapter 4

Pointers, references, and memory

Section 4.1

Pointers

A variable that stores... a memory address.

Definition

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++.

Syntax

Declaring and using a pointer

int a = 10; int* p = &a; // p holds the address of a std::cout << a; // 10 -- the value of a std::cout << &a; // e.g.: 0x7ffee... -- the address of a std::cout << p; // e.g.: 0x7ffee... -- the same address std::cout << *p; // 10 -- the value pointed to by p *p = 20; // modifies a through the pointer std::cout << a; // 20
  • & (address-of operator) : gives the memory address of a variable.
  • * (dereference operator) : accesses the value stored at the pointed-to address.
Remark

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.

Section 4.2

References

An alias for an existing variable — safer, but less flexible than a pointer.

Definition

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

int a = 10; int& ref = a; // ref is an alias for a ref = 20; // directly modifies a std::cout << a; // 20
Formula

Pointer vs reference

PointerReference
Can be nullYes (nullptr)No
ReassignableYesNo, fixed at initialization
Access syntaxDereferencing (*p)Direct, like the variable
Must be initializedNo (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).

Section 4.3

Dynamic memory

Allocating memory whose size is only known at runtime.

Syntax

new and delete

int* p = new int(42); // allocates an integer on the heap std::cout << *p; // 42 delete p; // frees the memory p = nullptr; // avoids a "dangling" pointer

All memory allocated with new must be freed with delete — C++ has no automatic garbage collector, unlike Python or Java.

Careful

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

Going further

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.

Chapter 5

Object-oriented programming

Section 5.1

Classes and objects

Grouping data and behavior into a single structure.

Definition

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.

Syntax

A simple class

class Student { public: std::string name; int age; // Constructor: called automatically on creation Student(std::string n, int a) { name = n; age = a; } void describe() { std::cout << name << " is " // Amina is 19 years old. return 0; }

The constructor has the same name as the class and runs automatically every time an object is created — useful to guarantee an object starts

Section 5.2

Encapsulation

Protecting an object's internal data from uncontrolled modification.

Definition

public, private, protected

  • public : accessible from anywhere outside the class.
  • private : accessible only from within the class itself.
  • protected : like private, but also accessible to classes that inherit from it.
Syntax

Getters and setters

class BankAccount { private: double balance; // inaccessible from outside public: BankAccount(double initialBalance) { balance = initialBalance; } double getBalance() { // "getter": controlled read access return balance; } void deposit(double amount) { // controlled modification if (amount > 0) balance += amount; } };

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.

Section 5.3

Inheritance

Building a new class from an existing one.

Syntax

A derived class

class Animal { public: std::string name; Animal(std::string n) { name = n; } void eat() { std::cout << name << " eats // Dog inherits from Animal public: Dog(std::string n) : Animal(n) {} // calls the parent constructor void bark() { std::cout << name << " barks!" << std::endl; } }; int main() { Dog rex("Rex"); rex.eat(); // inherited from Animal: "Rex eats." rex.bark(); // specific to Dog: "Rex barks!" return 0; }

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.

Going further

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

Chapter 6

The standard library (STL)

Section 6.1

std::vector — a dynamic array

The most widely used data structure in modern C++.

Definition

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.

Syntax

Working with a vector

#include <vector> std::vector<int> grades = {12, 15, 8}; grades.push_back(17); // adds to the end -> {12,15,8,17} std::cout << grades.size(); // 4 std::cout << grades[1]; // 15 (accessed by index, like an array) for (int n : grades) { // "for each" loop std::cout << n << " "; }
MethodRole
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
Section 6.2 – 6.3

std::string and other containers

The STL provides ready-to-use data structures for most common needs.

Syntax

std::string

#include <string> std::string firstName = "Yassine"; std::cout << firstName.length(); // 7 std::cout << firstName[0]; // 'Y' std::string fullName = firstName + " Idrissi"; // concatenation with +

Unlike std::string, C-style strings (char array[]) are lower level and generally avoided in modern C++.

Remark

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.

Hands-on labs

Practice with compiled code

Each exercise comes with an expandable correction — all corrections were compiled and run to verify their

All
Lab 1 · Basics
Lab 2 · Functions
Lab 3 · Pointers & OOP
Lab 1

Basics : types, operators, control

Working with variables, conditions, and loops.

Lab 1 · Ex 1
Exercise

Average of three grades

Ask the user for three real-number grades and display their average.

Correction
#include <iostream> using namespace std; int main() { double n1, n2, n3; cout << "Grade 1: "; cin >> n1; cout << "Grad

Verified with 12, 15.5, 9 : displayed average = 12.1667.

Lab 1 · Ex 2
Exercise

Even or odd

Read an integer and indicate whether it is even or odd.

Correction
#include <iostream> using namespace std; int main() { int n; cout << "Enter an integer: "; cin >> n; if (n % 2 == 0)
Lab 1 · Ex 3
Exercise

Multiplication table

Read an integer n and display its multiplication table from 1 to 10.

Correction
#include <iostream> using namespace std; int main() { int n; cout << "Number for the table: "; cin >> n; for (int i
Lab 2

Functions and arrays

Passing arrays to functions, returning values.

Lab 2 · Ex 1
Exercise

Maximum function

Write a function maximum(int a, int b) that returns the larger of the two.

Correction
#include <iostream> using namespace std; int maximum(int a, int b) { if (a > b) return a; return b; } int main() { c // 27 cout << maximum(50, 3) << endl; // 50 return 0; }
Lab 2 · Ex 2
Exercise

Reversing an array

Write a function reverse that reverses the order of an array's elements, in place (without an auxiliary array).

Correction
#include <iostream> using namespace std; void reverse(int arr[], int size) { for (int i = 0; i < size / 2; i++) { // 10 17 8 15 12 return 0; }

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.

Lab 2 · Ex 3
Exercise

Sum of an array's elements

Write a function sum that returns the sum of the elements of an integer array.

Correction
#include <iostream> using namespace std; int sum(int arr[], int size) { int s = 0; for (int i = 0; i < size; i++) s // 100 return 0; }
Lab 3

Pointers and object-oriented programming

Working with memory directly, then modeling with classes.

Lab 3 · Ex 1
Exercise

Swapping two integers using pointers

Write a function swap(int* a, int* b) that swaps the values of two integers using pointers.

Correction
#include <iostream> using namespace std; void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int ma // Before: x=5 y=12 // After: x=12 y=5 return 0; }

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.

Lab 3 · Ex 2
Exercise

Rectangle class

Create a Rectangle class (width, height) with methods area() and perimeter()by default.

Correction
#include <iostream> using namespace std; class Rectangle { private: double width, height; public: Rectangle(double w, // 15 cout << "Perimeter: " << r.perimeter() << endl; // 16 return 0; }
Lab 3 · Ex 3
Exercise

BankAccount class

Create a BankAccount with a private balance, a depositmethod, and a withdraw method that rejects a withdrawal if the balance is insufficient.

Correction
#include <iostream> using namespace std; class BankAccount { private: double balance; public: BankAccount(double bal // withdrawal rejected } }; int main() { BankAccount c(100.0); c.deposit(50.0); cout << "Balance after deposit: " << c.getBalance() << endl; // 150 c.withdraw(30.0); cout << "Balance after withdrawal: " << c.getBalance() << endl; // 120 bool ok = c.withdraw(1000.0); // rejected: insufficient balance cout << "Excessive withdrawal succeeded: " << ok << endl; // 0 (false) return 0; }

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.

Definition
Syntax / Formula
Example
Remark
Exercise
Correction
Key takeaways
★ Summary

What to absolutely remember

Compilation : preprocessor → compilation → linking → execution — a program must be recompiled after every change.
Strong typing : a variable's type is fixed at declaration and never changes.
Pointers : & gives an address, * dereferences — references are a safer but less flexible alias.
Dynamic memory : every new must have its delete — no automatic garbage collector.
OOP : classes, encapsulation (public/private), inheritance — structuring code around objects.
STL : std::vector and std::string for flexibly sized data, without reinventing the wheel.