# C++ from scratch

C++ is a compiled language used wherever speed and direct access to memory matter — game engines, browsers, databases, firmware. It is harder to get into than Python, but you can build your first working program on the very first evening.

## What kind of language it is

C++ grew out of C in the early 1980s: Bjarne Stroustrup added classes to it, and
later everything else the language is known for today. The two pluses are the
authors' joke: in C, the `++` operator increments a value by one.

The main difference from Python and JavaScript is compilation. The source code
is translated into machine instructions ahead of time, and you get a standalone
file that needs no interpreter or virtual machine to run. That is where the speed
comes from, and the strictness too: you learn about a type error when you build
the program, not when it is already running on a user's machine.

The second difference is that memory is under your control. The language does
not decide for you when to free what you allocated. That gives you control over
every byte and at the same time creates a whole class of bugs that simply do not
exist in other languages.

The language evolves through editions of the standard: C++11, C++14, C++17,
C++20, C++23. Modern C++ looks very different from 1990s textbooks — manual
memory allocation, pointers at every step and C-style arrays have given way to
containers and smart pointers. If the first program in a book starts with
`#include <stdio.h>` and `void main()`, the book is out of date.

## Where it is used

* **Games.** Unreal Engine is written in C++, and so is the game logic built on
  it.
* **Browsers and operating systems.** Page rendering engines, OS kernels,
  drivers.
* **Databases and high-load services.** Places where a millisecond costs money.
* **Embedded systems.** Microcontrollers, machine tools, car electronics.
  Arduino is a gentle way into this area: it uses a simplified C++ and you see
  the result on the board right away.
* **Engineering and graphics software.** CAD, image processing, audio and video.

What people usually do not write in it: simple websites, throwaway scripts, data
analysis. Languages with less manual work win there.

## What to install

You need two things: a compiler and an editor.

**The compiler.** On Linux, GCC is almost always already there; if not, install
it with the package manager (`sudo apt install build-essential`). On macOS, Clang
from the Command Line Tools plays that role — `xcode-select --install`. On Windows
there are two routes: Visual Studio Community with the "Desktop development with
C++" workload, or MinGW-w64 with the GCC compiler.

**The editor.** Visual Studio Code with the official C/C++ extension is a free
option that is good enough on any system. Visual Studio Community is a strong
free IDE for Windows. CLion is convenient, but paid.

Check that everything is in place:

```bash
g++ --version
```

If a version is printed, the compiler is found and you can write code. Working in
the terminal is not a whim here but the normal mode: you type the build and run
commands yourself. If the terminal is unfamiliar, see
[how to learn Linux from scratch](https://skillok.org/topics/learn-linux-from-scratch).

## Your first program

Create a file called `hello.cpp`:

```cpp
#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
```

What happens here: `#include <iostream>` brings in the input/output facilities.
`int main()` is the function where execution starts; there must be exactly one
in the whole program. `std::cout` is the output stream, `<<` sends a value into
it, and `std::endl` ends the line. `return 0` tells the system the program
finished without errors.

Build and run it:

```bash
g++ -std=c++17 -Wall -Wextra -o hello hello.cpp
./hello
```

The `-o hello` flag sets the name of the finished program (on Windows it becomes
`hello.exe`); without it you get a file called `a.out`. The `-Wall -Wextra` flags
turn on warnings — use them from day one, and the compiler will spot half of your
mistakes before you do. `-std=c++17` pins the edition of the standard.

The next step is input and variables:

```cpp
#include <iostream>
#include <string>

int main() {
    std::string name;
    int year = 0;

    std::cout << "Name: ";
    std::cin >> name;
    std::cout << "Year of birth: ";
    std::cin >> year;

    std::cout << name << ", you are about " << 2026 - year << " years old\n";
    return 0;
}
```

## How text becomes a program

Building happens in several steps, and knowing their names saves hours when you
read error messages.

1. **The preprocessor** pastes the contents of headers in place of the
   `#include` lines.
2. **The compiler** turns each `.cpp` file into an object file.
3. **The linker** stitches the object files and libraries into the finished
   program.

Hence two different kinds of errors. A compile error says something like
"expected ';'" or "no matching function" — the problem is in the text of one
file. A linker error — "undefined reference to …" — means the text is fine but no
file contains the function's implementation, or a library was not linked.

Once you have more than three files, the build commands go into CMake, and from
then on the same configuration builds on any system.

## Memory and pointers in plain words

A variable lives at some address. A pointer is a variable that stores that
address.

```cpp
int x = 5;
int* p = &x;      // p stores the address of x
*p = 8;           // writing through the address is the same as writing to x
std::cout << x;   // 8
```

The `&` before a name takes its address; an asterisk before a pointer reaches the
value at that address. A reference is simpler: `int& r = x;` is a second name for
the same variable — it cannot be left empty and cannot be redirected.

Memory comes in two kinds. Variables inside a function live on the stack and are
destroyed automatically when the block ends. Objects created with `new` live on
the heap and stay alive until someone deletes them.

```cpp
int* data = new int[100];
// ... work ...
delete[] data;          // forget this and you leak memory
```

This pair is the source of three classic disasters: a leak (forgot `delete`), a
double free (deleted twice) and a dangling pointer (used after deletion). The
modern answer to all three is not to write `new` by hand:

```cpp
#include <memory>
#include <vector>

std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4);                 // the size is now 4
auto ptr = std::make_unique<int>(42); // freed automatically
```

`std::vector` allocates and releases memory itself, and `std::unique_ptr` frees
its object when it goes out of scope. The principle behind this is called RAII:
owning a resource is tied to an object's lifetime. Understand it before classes —
it explains why careful C++ code almost never frees memory by hand.

## A study plan

The timings below assume an hour a day and are a guide, not a promise.

The first month goes on the basics: types, conditions, loops, functions, arrays
and `std::vector`, `std::string`. You are ready to move on after twenty problems
solved without hints: number crunching, strings, simple statistics over an array.

The second month is structs and classes: fields, methods, constructor and
destructor, splitting code into a `.h` header and a `.cpp` implementation. This
is also when you build a project from several files.

The third month is memory and everything around it: pointers, references,
passing arguments by value and by reference, smart pointers, RAII. A good sign
you have got it is being able to explain why copying a large object into a
function argument is expensive.

After that comes the standard library (containers, algorithms, iterators),
templates, and then choosing a direction: a game engine, embedded systems,
backend development. There is no such thing as "complete knowledge" of the
language, and that is fine.

## Common beginner mistakes

**An uninitialised pointer.** `int* p;` holds garbage, and writing through it
crashes the program somewhere random. Always assign an address or `nullptr`.

**Going past the end of an array.** In a vector of ten elements the last index is
nine. The compiler will not warn you, and the program may not even crash — it
will quietly corrupt neighbouring data.

**`=` instead of `==` in a condition.** `if (x = 5)` assigns five and is always
true. `-Wall` warns about this.

**A textbook from the last century.** Code with `#include <iostream.h>`,
`void main()` and `gets()` will not compile with a modern compiler, or will
compile with security holes.

Debugging is easier with a debugger than with printing values: `g++ -g` adds
debug information, and then `gdb ./hello` stops the program on the line you need
and shows the variables' values.

## Step-by-step plan

1. **Build your first program** — Install a compiler, write hello.cpp and build it with -Wall -Wextra.
2. **Language basics** — Solve twenty problems on conditions, loops, functions and vectors — no hints or ready solutions.
3. **Your own types** — Write a class with a constructor and destructor, split the declaration and implementation into two files.
4. **Memory** — Work through pointers and references, rewrite a new/delete example with std::vector and unique_ptr.
5. **A multi-file project** — Build a 300–500 line program with CMake and run it on another machine.

## Check yourself

1. What is x after this code: int x = 5; int* p = &x; *p = *p + 3;
2. Which g++ flag sets the name of the finished program?
   - -c
   - -o
   - -g
   - -I
3. Which function does a C++ program start executing from?
   - start
   - main
   - init
   - run
4. What does size() return for the vector after this code: std::vector<int> v = {1, 2, 3}; v.push_back(4);

## Sources

- [cppreference](https://en.cppreference.com/) — A complete reference for the language and the standard library
- [isocpp.org](https://isocpp.org/) — The standard committee's site: modern style guidelines and an FAQ
- [GCC documentation](https://gcc.gnu.org/onlinedocs/) — Compiler flags and what the warnings mean
- [LearnCpp.com](https://www.learncpp.com/) — A free, regularly updated C++ tutorial for beginners

---

https://skillok.org/articles/en/learn-cpp-from-scratch
