What is C++?
C++ is a cross-platform language that can be used to create high-performance applications. Developed by Bjarne Stroustrup as an extension of C, C++ gives programmers a high level of control over system resources and memory.
⚡ Performance
C++ compiles directly to machine code, making it one of the fastest languages available.
🎮 Game Development
Unreal Engine, Unity (C# with C++ core), and most AAA games are built with C++.
🖥️ System Programming
Operating systems, embedded systems, and real-time applications rely on C++.
Basic Syntax
C++ syntax is similar to C with added features like classes, namespaces, and streams.
#include <iostream> using namespace std; // Main function - entry point int main() { // Output to console cout << "Hello, World!" << endl; // Variables int age = 25; string name = "Alice"; bool isActive = true; double pi = 3.14159; // Input cout << "Enter your name: "; cin >> name; // Output with variables cout << "Hello, " << name << "! You are " << age << " years old." << endl; return 0; }
Pointers & Memory Management
C++ gives direct access to memory through pointers and allows dynamic memory allocation.
#include <iostream> using namespace std; int main() { // Basic pointer int value = 42; int* ptr = &value; // ptr holds address of value cout << "Value: " << *ptr << endl; // Dereference - prints 42 *ptr = 100; // Change value through pointer // Dynamic memory allocation int* arr = new int[5]; // Allocate array on heap for (int i = 0; i < 5; i++) { arr[i] = i * 10; } // Must free memory! delete[] arr; // Free array // Null pointer check int* ptr2 = nullptr; if (ptr2 != nullptr) { cout << *ptr2 << endl; } return 0; }
Classes & Object-Oriented Programming
C++ supports OOP with classes, inheritance, polymorphism, encapsulation, and abstraction.
#include <iostream> #include <string> using namespace std; class Animal { private: string name; int age; public: // Constructor with initializer list Animal(string n, int a) : name(n), age(a) {} // Virtual method for polymorphism virtual void makeSound() { cout << name << " makes a sound" << endl; } void display() { cout << "Name: " << name << ", Age: " << age << endl; } // Getter string getName() { return name; } }; // Inheritance class Dog : public Animal { private: string breed; public: Dog(string n, int a, string b) : Animal(n, a), breed(b) {} // Override (polymorphism) void makeSound() override { cout << getName() << " barks: Woof! Woof!" << endl; } void fetch() { cout << getName() << " is fetching the ball!" << endl; } }; int main() { Dog myDog("Buddy", 3, "Golden Retriever"); myDog.display(); myDog.makeSound(); // Polymorphic call myDog.fetch(); // Polymorphism with base class pointer Animal* animalPtr = &myDog; animalPtr->makeSound(); // Calls Dog's makeSound() return 0; }
Templates (Generic Programming)
Templates allow writing code that works with any data type, enabling generic programming.
#include <iostream> using namespace std; // Function template template <typename T> T max(T a, T b) { return (a > b) ? a : b; } // Class template template <typename T> class Box { private: T content; public: Box(T c) : content(c) {} void setContent(T c) { content = c; } T getContent() { return content; } void display() { cout << "Content: " << content << endl; } }; int main() { // Using function template cout << max(10, 20) << endl; // int version cout << max(3.14, 2.71) << endl; // double version cout << max('A', 'Z') << endl; // char version // Using class template Box<int> intBox(42); intBox.display(); Box<string> strBox("Hello Templates!"); strBox.display(); return 0; }
STL Containers
The Standard Template Library (STL) provides powerful container classes.
#include <iostream> #include <vector> #include <map> #include <set> #include <algorithm> using namespace std; int main() { // Vector (dynamic array) vector<int> numbers = {1, 2, 3, 4, 5}; numbers.push_back(6); numbers.pop_back(); for (int n : numbers) { cout << n << " "; } cout << endl; // Map (key-value pairs) map<string, int> scores; scores["Alice"] = 95; scores["Bob"] = 87; scores["Charlie"] = 92; for (auto& pair : scores) { cout << pair.first << ": " << pair.second << endl; } // Set (unique elements) set<int> uniqueNumbers = {1, 2, 2, 3, 3, 4}; cout << "Unique count: " << uniqueNumbers.size() << endl; // Algorithm: sort, find, etc. vector<int> nums = {5, 2, 8, 1, 9}; sort(nums.begin(), nums.end()); auto it = find(nums.begin(), nums.end(), 8); if (it != nums.end()) { cout << "Found 8 at position: " << (it - nums.begin()) << endl; } return 0; }
Smart Pointers (Modern C++)
Modern C++ provides smart pointers that automatically manage memory, preventing leaks.
#include <iostream> #include <memory> using namespace std; class Resource { public: Resource() { cout << "Resource acquired" << endl; } ~Resource() { cout << "Resource released" << endl; } void doWork() { cout << "Working..." << endl; } }; int main() { // unique_ptr - exclusive ownership unique_ptr<Resource> ptr1 = make_unique<Resource>(); ptr1->doWork(); // Cannot copy unique_ptr, only move unique_ptr<Resource> ptr2 = move(ptr1); // ptr1 is now null // shared_ptr - shared ownership (reference counted) shared_ptr<Resource> shared1 = make_shared<Resource>(); { shared_ptr<Resource> shared2 = shared1; // Reference count = 2 shared2->doWork(); cout << "Use count: " << shared1.use_count() << endl; } // shared2 destroyed, count = 1 cout << "Use count after: " << shared1.use_count() << endl; // Resource automatically released when last shared_ptr destroyed return 0; }
🛠 Project: Simple Game Engine (Text-Based)
Create a simple text-based game with player stats, enemies, and combat.
#include <iostream> #include <string> #include <vector> #include <cstdlib> #include <ctime> using namespace std; class Character { protected: string name; int health; int strength; public: Character(string n, int h, int s) : name(n), health(h), strength(s) {} bool isAlive() { return health > 0; } void takeDamage(int damage) { health -= damage; if (health < 0) health = 0; cout << name << " takes " << damage << " damage! Health: " << health << endl; } int attack() { int damage = (rand() % strength) + 5; cout << name << " attacks for " << damage << " damage!" << endl; return damage; } void display() { cout << "=== " << name << " ===\nHealth: " << health << "\nStrength: " << strength << endl; } string getName() { return name; } }; class Player : public Character { private: int experience; int level; public: Player(string n) : Character(n, 100, 15), experience(0), level(1) {} void gainExperience(int exp) { experience += exp; if (experience >= level * 100) { level++; health += 20; strength += 5; cout << "*** LEVEL UP! Now level " << level << " ***" << endl; } } void heal() { health = 100 + (level - 1) * 20; cout << name << " is fully healed!" << endl; } void display() { Character::display(); cout << "Level: " << level << "\nExperience: " << experience << "/" << level * 100 << endl; } }; class Enemy : public Character { public: Enemy(string n, int h, int s) : Character(n, h, s) {} }; int main() { srand(time(nullptr)); string playerName; cout << "Enter your hero's name: "; cin >> playerName; Player hero(playerName); vector<Enemy> enemies = { Enemy("Goblin", 30, 8), Enemy("Orc", 50, 12), Enemy("Dragon", 80, 20) }; cout << "\n=== Welcome to the Arena! ===\n" << endl; for (int i = 0; i < enemies.size() && hero.isAlive(); i++) { Enemy& currentEnemy = enemies[i]; cout << "\n--- Battle " << i + 1 << ": Fight " << currentEnemy.getName() << "! ---\n" << endl; while (hero.isAlive() && currentEnemy.isAlive()) { hero.display(); currentEnemy.display(); cout << "\n1. Attack\n2. Heal\nChoose action: "; int choice; cin >> choice; if (choice == 1) { int damage = hero.attack(); currentEnemy.takeDamage(damage); if (currentEnemy.isAlive()) { damage = currentEnemy.attack(); hero.takeDamage(damage); } } else if (choice == 2) { hero.heal(); } } if (!currentEnemy.isAlive()) { int exp = 50 * (i + 1); hero.gainExperience(exp); cout << "Victory! Gained " << exp << " experience!\n" << endl; } } if (hero.isAlive()) { cout << "\n🎉 Congratulations! You defeated all enemies! 🎉\n"; } else { cout << "\n💀 Game Over! Better luck next time! 💀\n"; } return 0; }