Skip to content

Latest commit

 

History

History
69 lines (55 loc) · 1.67 KB

File metadata and controls

69 lines (55 loc) · 1.67 KB

C++ Language Crash Course

1. Introduction

C++ is a superset of C that introduces Object-Oriented Programming (OOP) and the Standard Template Library (STL). It offers both low-level memory control (like C) and high-level abstractions.

2. Hello World in C++

Instead of <stdio.h> and printf(), C++ uses <iostream> and streams (std::cout).

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
  • std::cout: Character Output stream.
  • <<: Stream insertion operator.
  • std::endl: End line (also flushes the buffer).

3. Namespaces

Namespaces prevent name conflicts. You can avoid typing std:: everywhere by using:

using namespace std;

(Note: Avoid using this in header files to prevent global namespace pollution).

4. References vs Pointers

C++ introduces references (&), which act as safe aliases to variables, avoiding pointer arithmetic.

int x = 10;
int& ref = x; // ref is now an alias for x
ref = 20;     // x is now 20

5. Classes & Objects (OOP)

class Person {
private:
    std::string name;

public:
    // Constructor
    Person(std::string n) : name(n) {}

    // Method
    void greet() {
        std::cout << "Hi, I am " << name << std::endl;
    }
};

int main() {
    Person p("Alice");
    p.greet();
}

6. Dynamic Memory (new / delete)

Instead of malloc() and free(), C++ uses new and delete.

int* p = new int(10); // Allocate integer initialized to 10
delete p;             // Free memory

int* arr = new int[5]; // Allocate array
delete[] arr;          // Free array

(Modern C++ discourages raw new/delete in favor of Smart Pointers).