Back-end · formation gratuite

C++ Training

Learn C++, a powerful and versatile programming language

  • Avancé
  • 13 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to C++

C++ is a compiled, multi-paradigm programming language created by Bjarne Stroustrup in 1983. C++ extends the C language with object-oriented features, templates, and many modern improvements.

⚙️ What is C++?

C++ is a compiled, multi-paradigm programming language (procedural, object-oriented, generic). C++ is a mid-level language that combines the power and control of C with high-level features.

💡 Why is C++ so important?

  1. Maximum performance - Used for applications requiring optimal performance (video games, real-time systems)
  2. Versatility - Supports multiple programming paradigms (procedural, OOP, generic)
  3. Standard Template Library (STL) - Rich library of containers and algorithms
  4. Industry - Widely used in game development, embedded systems, high-frequency finance
  5. Memory control - Manual or automatic management depending on needs
  6. Modern standard - C++11/14/17/20 bring modern features

🚀 Why learn C++?

C++ is a powerful language that opens many opportunities in software development. Here are the main reasons to learn C++:

  • ✅ Performance - Applications requiring maximum performance
  • ✅ Video games - Industry standard for game engines (Unreal, Unity)
  • ✅ Embedded systems - Programming of critical systems
  • ✅ Finance - High-frequency trading, financial systems
  • ✅ Solid foundation - Understanding C++ facilitates learning other languages
  • ✅ Career - Highly sought after in the game and systems industry

📋 Prerequisites to learn C++

To learn C++ effectively, it is recommended to have a foundation in programming (variables, conditions, loops).

  • ✅ Programming basics - Understanding basic concepts (variables, conditions, loops)
  • ✅ C language (optional) - Having C basics facilitates learning C++
  • ✅ Patience - C++ requires attention to detail

💡 Important note: To compile C++ code, you need a compiler like GCC (GNU Compiler Collection) or Clang. On Linux, GCC is often preinstalled. On Windows, you can install MinGW or use Visual Studio. On macOS, install Xcode Command Line Tools.

🎯 C++ Use Cases

C++ is used in many critical domains:

  • 🎮 Video games - Game engines (Unreal Engine, Unity)
  • 🖥️ Embedded systems - Microcontrollers, IoT, real-time systems
  • 💼 Finance - High-frequency trading, financial systems
  • 🔧 System programming - Drivers, compilers, system tools
  • 📡 Networks - Network protocols, high-performance servers
  • 🔬 Scientific computing - Applications requiring intensive calculations
  • 💾 Databases - Database engines
  • 🌐 Web servers - High-performance web servers

📝 Basic Syntax

C++ is a compiled programming language. C++ uses braces {} to define code blocks and requires a semicolon ; at the end of each statement.

// Premier programme C++
#include 
using namespace std;

int main() {
    cout << "Bonjour, monde !" << endl;
    return 0;
}

// Variables
int age = 25;
string nom = "NiangProgrammeur";

// Affichage formaté
cout << "Je m'appelle " << nom << " et j'ai " << age << " ans" << endl;

// Opérations simples
int resultat = 10 + 5;
cout << "10 + 5 = " << resultat << endl;
}

💡 Important points about C++ syntax:

  • C++ uses braces {} to define code blocks
  • Comments use // for a single line or /* */ for multiple lines
  • Semicolon required ; at the end of each statement
  • Strings use double quotes "
  • Functions must be declared before use (or via headers)
  • The entry point is the main() function that returns an int

🔍 Detailed syntax example

Here is a complete example showing several aspects of C++ syntax:

#include 
#include 
using namespace std;

// Définition d'une fonction
int calculer_moyenne(int nombres[], int taille) {
    if (taille == 0) {
        return 0;
    }
    int somme = 0;
    for (int i = 0; i < taille; i++) {
        somme += nombres[i];
    }
    return somme / taille;
}

// Classe simple
class Personne {
public:
    string nom;
    int age;
    
    void afficher() {
        cout << "Nom: " << nom << ", Age: " << age << endl;
    }
};

// Fonction principale
int main() {
    int notes[] = {15, 18, 12, 20, 16};
    int moyenne = calculer_moyenne(notes, 5);
    cout << "La moyenne est : " << moyenne << endl;
    
    // Utilisation d'une classe
    Personne p;
    p.nom = "Bassirou";
    p.age = 25;
    p.afficher();
    
    return 0;
}

🔤 Variables

In C++, variables must be declared with a type before use. C++ is a statically typed language.

#include 
#include 
using namespace std;

int main() {
    // Déclaration de variables
    int age = 30;                    // Entier
    float prix = 19.99f;             // Nombre décimal (simple précision)
    double decimal = 3.14159;         // Nombre décimal (double précision)
    char lettre = 'A';               // Caractère unique
    string nom = "C++";              // Chaîne de caractères (C++)
    bool est_vrai = true;            // Booléen
    
    // Affichage avec cout
    cout << "Age: " << age << endl;
    cout << "Prix: " << prix << endl;
    cout << "Decimal: " << decimal << endl;
    cout << "Lettre: " << lettre << endl;
    cout << "Nom: " << nom << endl;
    cout << "Est vrai: " << est_vrai << endl;
    
    // Déclaration puis assignation
    int nombre;
    nombre = 10;
    cout << "Nombre: " << nombre << endl;
    
    // Constantes avec const
    const int TAILLE = 50;
    const string MESSAGE = "Bonjour";
    
    // Constantes avec constexpr (C++11)
    constexpr double PI = 3.14159;
    constexpr int MAX_SIZE = 100;
    
    // Noms de variables valides
    int age_utilisateur = 25;
    string nom_utilisateur = "Bassirou";
    float _prive = 3.14;  // Possible mais non recommandé
    
    return 0;
}

📌 Rules for variable names:

  • Must start with a letter or underscore _
  • Can contain letters, numbers, and underscores
  • Cannot contain spaces or special characters
  • Case sensitive (age ≠ Age)
  • Cannot be C++ keywords (if, for, int, class, etc.)
  • Convention: use camelCase or snake_case for variables

📊 Data Types

C++ has several basic (primitive) data types. Here are the main types available in C++:

#include 
#include 
using namespace std;

int main() {
    // Types entiers
    char c = 'A';              // 1 octet (-128 à 127 ou 0 à 255)
    short s = 100;             // 2 octets (-32768 à 32767)
    int i = 1000;              // 4 octets (généralement)
    long l = 100000L;          // 4 ou 8 octets
    long long ll = 1000000LL;  // 8 octets
    
    // Types entiers non signés
    unsigned char uc = 200;
    unsigned int ui = 5000;
    unsigned long ul = 100000UL;
    
    // Types décimaux
    float f = 3.14f;           // 4 octets (simple précision)
    double d = 3.14159;        // 8 octets (double précision)
    long double ld = 3.141592653589793L;  // 10 ou 16 octets
    
    // Type booléen
    bool est_vrai = true;
    bool est_faux = false;
    
    // Chaînes de caractères (C++)
    string chaine = "Hello";   // Classe string (C++)
    char tableau[] = "World";  // Tableau de caractères (style C)
    
    // Affichage avec cout
    cout << "char: " << c << endl;
    cout << "int: " << i << endl;
    cout << "float: " << f << endl;
    cout << "double: " << d << endl;
    cout << "bool: " << est_vrai << endl;
    cout << "string: " << chaine << endl;
    
    // Taille des types (en octets)
    cout << "Taille de int: " << sizeof(int) << " octets" << endl;
    cout << "Taille de float: " << sizeof(float) << " octets" << endl;
    cout << "Taille de double: " << sizeof(double) << " octets" << endl;
    
    return 0;
}

📚 C++ Data Types:

  • char - Character (1 byte)
  • int - Integer (generally 4 bytes)
  • float - Single precision decimal number (4 bytes)
  • double - Double precision decimal number (8 bytes)
  • void - Empty type (for functions without return)
  • bool - Boolean (true/false)
  • string - Character string (C++)
  • short, long, long long - Integer variants
  • unsigned - Modifier for unsigned integers

🔢 Operators

C++ supports arithmetic, comparison, logical, assignment, and pointer operators:

#include 
#include   // Pour pow()
using namespace std;

int main() {
    int a = 10, b = 3;
    
    // Opérateurs arithmétiques
    cout << a << " + " << b << " = " << (a + b) << endl;      // Addition: 13
    cout << a << " - " << b << " = " << (a - b) << endl;      // Soustraction: 7
    cout << a << " * " << b << " = " << (a * b) << endl;      // Multiplication: 30
    cout << a << " / " << b << " = " << (a / b) << endl;      // Division entière: 3
    cout << a << " % " << b << " = " << (a % b) << endl;      // Modulo (reste): 1
    
    // Division avec float
    float resultat = (float)a / b;
    cout << a << " / " << b << " = " << resultat << endl;     // Division: 3.33
    
    // Puissance (nécessite cmath)
    double puissance = pow(a, b);
    cout << a << "^" << b << " = " << puissance << endl;      // Puissance: 1000
    
    // Opérateurs de comparaison
    cout << (a > b) << endl;   // true (1)
    cout << (a < b) << endl;   // false (0)
    cout << (a >= b) << endl;  // true (1)
    cout << (a <= b) << endl;  // false (0)
    cout << (a == b) << endl;  // false (0)
    cout << (a != b) << endl;  // true (1)
    
    // Opérateurs logiques
    bool x = true, y = false;
    cout << (x && y) << endl;  // ET logique: false (0)
    cout << (x || y) << endl;  // OU logique: true (1)
    cout << !x << endl;       // NON logique: false (0)
    
    // Opérateurs d'assignation
    int c = 5;
    c += 3;  // Équivalent à c = c + 3 (c devient 8)
    c -= 2;  // Équivalent à c = c - 2 (c devient 6)
    c *= 2;  // Équivalent à c = c * 2 (c devient 12)
    c /= 3;  // Équivalent à c = c / 3 (c devient 4)
    c %= 3;  // Équivalent à c = c % 3 (c devient 1)
    
    // Opérateurs d'incrémentation/décrémentation
    int i = 5;
    cout << "i = " << i++ << endl;  // Post-incrémentation: affiche 5, puis i = 6
    cout << "i = " << ++i << endl;  // Pré-incrémentation: i = 7, puis affiche 7
    
    return 0;
}

🔀 Conditional Structures

The C++ language uses if, else if, and else for conditions. Code blocks are delimited by braces {}.

#include 
using namespace std;

int main() {
    // Structure if simple
    int age = 20;
    
    if (age >= 18) {
        cout << "Vous êtes majeur" << endl;
    } else {
        cout << "Vous êtes mineur" << endl;
    }
    
    // Structure if/else if/else
    age = 15;
    
    if (age >= 18) {
        cout << "Vous êtes majeur" << endl;
        cout << "Vous pouvez voter" << endl;
    } else if (age >= 13) {
        cout << "Vous êtes adolescent" << endl;
    } else if (age >= 6) {
        cout << "Vous êtes enfant" << endl;
    } else {
        cout << "Vous êtes un bébé" << endl;
    }
    
    // Conditions multiples
    int note = 85;
    string mention;
    
    if (note >= 90) {
        mention = "Excellent";
    } else if (note >= 80) {
        mention = "Très bien";
    } else if (note >= 70) {
        mention = "Bien";
    } else if (note >= 60) {
        mention = "Assez bien";
    } else {
        mention = "Insuffisant";
    }
    
    cout << "Votre mention : " << mention << endl;
    
    // Opérateur ternaire (expression conditionnelle)
    age = 20;
    string statut = (age >= 18) ? "Majeur" : "Mineur";
    cout << statut << endl;
    
    // Conditions avec &&/||
    age = 25;
    bool permis = true;
    
    if (age >= 18 && permis) {
        cout << "Vous pouvez conduire" << endl;
    } else {
        cout << "Vous ne pouvez pas conduire" << endl;
    }
    
    return 0;
}

🔄 Loops

The C++ language offers several types of loops: for (to iterate a defined number of times), while (to repeat while a condition is true), and do-while (executes at least once):

#include 
#include 
using namespace std;

int main() {
    // Boucle for classique
    for (int i = 0; i < 5; i++) {
        cout << i << " ";  // Affiche 0, 1, 2, 3, 4
    }
    cout << endl;
    
    // Boucle for avec range (C++11)
    vector nombres = {1, 2, 3, 4, 5};
    for (int n : nombres) {
        cout << n << " ";  // Affiche 1, 2, 3, 4, 5
    }
    cout << endl;
    
    // Boucle for avec pas
    for (int i = 0; i < 10; i += 2) {
        cout << i << " ";  // Affiche 0, 2, 4, 6, 8
    }
    cout << endl;
    
    // Boucle for avec vector
    vector fruits = {"pomme", "banane", "orange"};
    for (const string& fruit : fruits) {
        cout << "J'aime les " << fruit << endl;
    }
    
    // Boucle while
    int compteur = 0;
    while (compteur < 5) {
        cout << compteur << " ";
        compteur++;
    }
    cout << endl;
    
    // Boucle do-while (exécute au moins une fois)
    int i = 0;
    do {
        cout << i << " ";
        i++;
    } while (i < 5);
    cout << endl;
    
    // Boucle while avec break
    compteur = 0;
    while (true) {
        cout << compteur << " ";
        compteur++;
        if (compteur >= 5) {
            break;  // Sortir de la boucle
        }
    }
    cout << endl;
    
    // continue (passer à l'itération suivante)
    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {  // Si i est pair
            continue;       // Passer au suivant
        }
        cout << i << " ";  // Affiche seulement les impairs: 1, 3, 5, 7, 9
    }
    cout << endl;
    
    return 0;
}

⚙️ Functions

Functions allow code reuse. In C++, we define a function with its return type, name, and parameters. Functions can take parameters and return values with return.

#include 
#include 
using namespace std;

// Fonction simple (sans paramètres)
void dire_bonjour() {
    cout << "Bonjour !" << endl;
}

// Fonction avec paramètres
string saluer(string nom) {
    return "Bonjour, " + nom + " !";
}

// Fonction avec plusieurs paramètres
int additionner(int a, int b) {
    return a + b;
}

// Fonction avec paramètres par défaut
string saluer_personne(string nom, string message = "Bonjour") {
    return message + ", " + nom + " !";
}

// Fonction avec surcharge (même nom, paramètres différents)
int multiplier(int a, int b) {
    return a * b;
}

double multiplier(double a, double b) {
    return a * b;
}

// Fonction inline (pour petites fonctions)
inline int carre(int x) {
    return x * x;
}

int main() {
    // Appel de fonctions
    dire_bonjour();
    
    string message = saluer("C++");
    cout << message << endl;  // "Bonjour, C++ !"
    
    int resultat = additionner(5, 3);
    cout << resultat << endl;  // 8
    
    cout << saluer_personne("Bassirou") << endl;              // "Bonjour, Bassirou !"
    cout << saluer_personne("Bassirou", "Salut") << endl;     // "Salut, Bassirou !"
    
    // Surcharge de fonctions
    cout << multiplier(5, 3) << endl;        // 15 (int)
    cout << multiplier(5.5, 3.2) << endl;    // 17.6 (double)
    
    // Fonction inline
    cout << carre(5) << endl;  // 25
    
    return 0;
}

🏛️ Classes and Objects

In C++, classes allow creating custom types with properties (members) and methods (member functions).

#include 
#include 
using namespace std;

// Définition d'une classe
class Personne {
private:
    string nom;
    int age;
    
public:
    // Constructeur
    Personne(string n, int a) {
        nom = n;
        age = a;
    }
    
    // Méthodes (getters)
    string getNom() {
        return nom;
    }
    
    int getAge() {
        return age;
    }
    
    // Méthodes (setters)
    void setNom(string n) {
        nom = n;
    }
    
    void setAge(int a) {
        age = a;
    }
    
    // Méthode pour afficher
    void afficher() {
        cout << "Nom: " << nom << ", Age: " << age << endl;
    }
};

int main() {
    // Création d'objets
    Personne p1("Bassirou", 25);
    Personne p2("Aminata", 30);
    
    // Utilisation des méthodes
    p1.afficher();
    p2.afficher();
    
    // Modification via setters
    p1.setAge(26);
    p1.afficher();
    
    // Accès via getters
    cout << "Nom de p1: " << p1.getNom() << endl;
    cout << "Age de p1: " << p1.getAge() << endl;
    
    return 0;
}

🔗 Inheritance

Inheritance allows a class to derive from another class and inherit its members.

#include 
#include 
using namespace std;

// Classe de base
class Animal {
protected:
    string nom;
    
public:
    Animal(string n) : nom(n) {}
    
    void manger() {
        cout << nom << " mange" << endl;
    }
    
    virtual void faireBruit() {
        cout << nom << " fait un bruit" << endl;
    }
};

// Classe dérivée
class Chien : public Animal {
public:
    Chien(string n) : Animal(n) {}
    
    void faireBruit() override {
        cout << nom << " aboie" << endl;
    }
    
    void aboyer() {
        cout << nom << " aboie fort !" << endl;
    }
};

// Classe dérivée
class Chat : public Animal {
public:
    Chat(string n) : Animal(n) {}
    
    void faireBruit() override {
        cout << nom << " miaule" << endl;
    }
};

int main() {
    Chien chien("Rex");
    Chat chat("Mimi");
    
    chien.manger();      // Hérité de Animal
    chien.faireBruit();  // Surchargé dans Chien
    chien.aboyer();      // Spécifique à Chien
    
    chat.manger();       // Hérité de Animal
    chat.faireBruit();   // Surchargé dans Chat
    
    return 0;
}

🔄 Polymorphisme

Le polymorphisme permet à des objets de classes différentes d'être traités de manière uniforme via une interface commune. En C++, cela se fait avec des fonctions virtuelles.

#include 
#include 
using namespace std;

// Classe de base avec fonction virtuelle
class Forme {
public:
    virtual double calculerAire() = 0;  // Fonction virtuelle pure
    virtual void afficher() {
        cout << "Forme" << endl;
    }
};

// Classe dérivée
class Cercle : public Forme {
private:
    double rayon;
    
public:
    Cercle(double r) : rayon(r) {}
    
    double calculerAire() override {
        return 3.14159 * rayon * rayon;
    }
    
    void afficher() override {
        cout << "Cercle de rayon " << rayon << endl;
    }
};

// Classe dérivée
class Rectangle : public Forme {
private:
    double largeur, hauteur;
    
public:
    Rectangle(double l, double h) : largeur(l), hauteur(h) {}
    
    double calculerAire() override {
        return largeur * hauteur;
    }
    
    void afficher() override {
        cout << "Rectangle " << largeur << "x" << hauteur << endl;
    }
};

int main() {
    // Polymorphisme avec pointeurs
    Forme* forme1 = new Cercle(5.0);
    Forme* forme2 = new Rectangle(4.0, 6.0);
    
    forme1->afficher();
    cout << "Aire: " << forme1->calculerAire() << endl;
    
    forme2->afficher();
    cout << "Aire: " << forme2->calculerAire() << endl;
    
    // Polymorphisme avec vector
    vector formes;
    formes.push_back(new Cercle(3.0));
    formes.push_back(new Rectangle(2.0, 4.0));
    
    for (Forme* f : formes) {
        f->afficher();
        cout << "Aire: " << f->calculerAire() << endl;
    }
    
    // Libération mémoire
    delete forme1;
    delete forme2;
    for (Forme* f : formes) {
        delete f;
    }
    
    return 0;
}

📦 Templates

Les templates permettent de créer des fonctions et classes génériques qui fonctionnent avec différents types de données. C'est une fonctionnalité puissante de C++.

#include 
#include 
using namespace std;

// Template de fonction
template
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

// Template de classe
template
class Pile {
private:
    T* elements;
    int taille;
    int sommet;
    
public:
    Pile(int t) : taille(t), sommet(-1) {
        elements = new T[taille];
    }
    
    ~Pile() {
        delete[] elements;
    }
    
    void empiler(T element) {
        if (sommet < taille - 1) {
            elements[++sommet] = element;
        }
    }
    
    T depiler() {
        if (sommet >= 0) {
            return elements[sommet--];
        }
        return T();
    }
    
    bool estVide() {
        return sommet == -1;
    }
};

int main() {
    // Utilisation du template de fonction
    cout << maximum(10, 20) << endl;           // 20 (int)
    cout << maximum(3.5, 2.8) << endl;         // 3.5 (double)
    cout << maximum('a', 'z') << endl;         // 'z' (char)
    cout << maximum(string("abc"), string("xyz")) << endl;  // "xyz" (string)
    
    // Utilisation du template de classe
    Pile pileInt(10);
    pileInt.empiler(10);
    pileInt.empiler(20);
    pileInt.empiler(30);
    
    while (!pileInt.estVide()) {
        cout << pileInt.depiler() << " ";
    }
    cout << endl;
    
    Pile pileString(10);
    pileString.empiler("Premier");
    pileString.empiler("Deuxième");
    pileString.empiler("Troisième");
    
    while (!pileString.estVide()) {
        cout << pileString.depiler() << " ";
    }
    cout << endl;
    
    return 0;
}

📚 Standard Template Library (STL)

The STL is a powerful C++ library that provides ready-to-use containers, iterators, and algorithms.

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main() {
    // Vector (tableau dynamique)
    vector nombres = {3, 1, 4, 1, 5, 9, 2, 6};
    
    nombres.push_back(8);  // Ajouter un élément
    nombres.pop_back();    // Retirer le dernier élément
    
    cout << "Taille: " << nombres.size() << endl;
    
    // Parcourir avec range-based for (C++11)
    for (int n : nombres) {
        cout << n << " ";
    }
    cout << endl;
    
    // Trier avec algorithm
    sort(nombres.begin(), nombres.end());
    cout << "Trié: ";
    for (int n : nombres) {
        cout << n << " ";
    }
    cout << endl;
    
    // List (liste doublement chaînée)
    list mots = {"C++", "est", "puissant"};
    mots.push_back("!");
    mots.push_front("Le");
    
    for (const string& mot : mots) {
        cout << mot << " ";
    }
    cout << endl;
    
    // Map (dictionnaire)
    map ages;
    ages["Bassirou"] = 25;
    ages["Aminata"] = 30;
    ages["Ibrahima"] = 28;
    
    for (const auto& paire : ages) {
        cout << paire.first << " a " << paire.second << " ans" << endl;
    }
    
    // Algorithmes STL
    vector vec = {1, 2, 3, 4, 5};
    
    // Trouver un élément
    auto it = find(vec.begin(), vec.end(), 3);
    if (it != vec.end()) {
        cout << "Trouvé: " << *it << endl;
    }
    
    // Compter
    int count = count_if(vec.begin(), vec.end(), [](int x) { return x > 2; });
    cout << "Éléments > 2: " << count << endl;
    
    // Transformer
    transform(vec.begin(), vec.end(), vec.begin(), [](int x) { return x * 2; });
    cout << "Doublé: ";
    for (int n : vec) {
        cout << n << " ";
    }
    cout << endl;
    
    return 0;
}

💡 Important note: C++ offers precise control over memory with new and delete (or malloc/free C style). In modern C++, prefer STL containers (vector, string) that automatically manage memory!

🎓 Next Steps

Congratulations! You now have a solid foundation in C++.

✅ What you have learned:

  • C++ syntax and variables
  • Data types (int, float, double, char, bool, string)
  • Operators (arithmetic, comparison, logical)
  • Conditional structures (if, else if, else, switch)
  • Loops (for, while, do-while)
  • Functions (definition, parameters, return, overloading)
  • Classes and objects (encapsulation, constructors)
  • Inheritance and polymorphism

🚀 To go further:

  • 📚 Templates - Advanced generic programming
  • 🔧 STL - Standard Template Library (containers, algorithms)
  • 💾 Memory management - Smart pointers, RAII
  • 🌐 Multithreading - Concurrent programming
  • 📊 Design patterns - Design patterns in C++
  • 🎮 Game development - Game development with C++
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?