Skip to content
LumenaryAcademy
Foundations 45 min

First steps with C++

Where C++ came from, what it is for, and how source code becomes a running program.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Why learn C++ now?

Open a web browser and you are running millions of lines of C++. The same is true of most game engines, the large databases, the compilers that build other languages (GCC and LLVM are written in it), the engines inside machine-learning frameworks, flight software, trading systems, and a good deal of the operating system under your fingers. C++ is where software goes when it must be fast, must control exactly how memory is laid out, and must still be organised into large, maintainable pieces.

That combination is rare. Python lets you build abstractions easily but pays for them at run time. C gives you the machine but few tools for structuring big programs. C++ was designed to give you both: you can write a Matrix class or a generic sorting function that reads like a high-level library, and the compiler turns it into code as fast as anything you would have written by hand.

The price is complexity. C++ is more than forty years old, it kept compatibility with C and with its own past at almost every step, and so it carries several ways of doing most things, including some that are now considered mistakes. It also trusts you: if a program reads past the end of an array, the language does not promise an error message, and the consequences can range from a wrong answer to a security hole. Government security agencies and large companies have, in recent years, published guidance encouraging memory-safe languages for new code for exactly this reason, and the C++ community is responding with safer defaults, hardened standard libraries and tools that catch mistakes.

This course teaches modern C++: the C++20 and C++23 that experienced engineers write today, where most of the dangerous older habits are unnecessary. You will learn the old forms too, because you will read them in existing code, but you will learn first what to reach for.

History & global context

From C with Classes to C++23

In 1979 Bjarne Stroustrup, a Danish computer scientist working at Bell Labs in New Jersey, started adding classes to C. He had used Simula, a language with classes and objects, for simulation work in his doctoral research in Cambridge, and had found it wonderful for organising programs but far too slow. C was fast and close to the machine but gave little help with structure. His "C with Classes" aimed to have both. It was renamed C++ in 1983 (++ is C's increment operator: "one more than C"), and the first commercial release, with the first edition of his book The C++ Programming Language, came in 1985. That early compiler, Cfront, translated C++ into C and let a C compiler finish the job.

C++ spread quickly through the late 1980s and 1990s, and in 1998 it became an international standard, ISO/IEC 14882, maintained since then by a committee of volunteers from companies, universities and national bodies (its formal name is WG21). The milestones you will hear people mention:

StandardWhat it brought
C++98 / C++03The first standard: templates, exceptions, the Standard Template Library (containers, iterators, algorithms)
C++11The great modernisation: auto, lambdas, move semantics, smart pointers, threads, range-for. People speak of "pre-11" and "modern" C++
C++14, C++17Refinements: std::optional, std::variant, std::string_view, structured bindings, if constexpr
C++20Concepts, ranges, coroutines, modules, std::format, std::jthread
C++23std::print, std::expected, more ranges, import std;, explicit object parameters
C++26Completed by the committee in 2025: static reflection, contracts, std::execution; compilers are implementing it during 2026

Since C++11 a new standard has appeared every three years. Compilers implement features gradually, so "is this available?" is a real question; the compiler support table answers it. This course uses what GCC 14 supports with -std=c++23.

Three design ideas explain most of the language:

  • The zero-overhead principle. A feature you do not use costs you nothing, and a feature you do use should cost no more than the best code you could write by hand to do the same job. That is why C++ has no garbage collector running in the background and why its containers and algorithms compile down to tight loops.
  • Direct access to the hardware. You can say exactly how big an integer is, where an object lives in memory, and how bytes are laid out, which is what operating systems, drivers and game engines need.
  • Compatibility. Code written decades ago still compiles. This is a huge practical asset (nobody has to rewrite a working codebase to move to a new compiler) and the main reason the language is so large.
DefinitionsH

From source file to running program

C++ is a compiled language. You do not run the text you write; a compiler first translates it into machine code for your processor, and you run the result. Understanding the steps saves hours of confusion later, because each step has its own kind of error.

Definition— translation unit

One source file (conventionally .cpp) together with everything its #include lines pull in. The compiler works on one translation unit at a time and knows nothing about the others while it does.

Definition— preprocessor, compiler, linker

The preprocessor handles lines starting with #: #include <print> pastes in the contents of a header, a file of declarations. The compiler then checks and translates the translation unit into an object file of machine code. The linker joins object files and libraries (including the compiled part of the standard library) into one executable. One command, such as g++ main.cpp -o main, normally runs all three.

Definition— the standard library

The library every conforming C++ implementation ships: strings, containers such as std::vector and std::map, algorithms, input and output, threads, time, random numbers and much more. Its names live in the namespace std, so you write std::vector. GCC's implementation is called libstdc++, Clang's is libc++, and Microsoft's is the MSVC STL.

Definition— main

The function where every C++ program starts. It returns an int to the operating system: 0 means success. main is the one function where you may leave the return out, in which case it returns 0.

An error from the compiler (a type mismatch, a misspelt name) means the code was never translated. An error from the linker ("undefined reference to ...") means each file compiled but a function that was declared was never defined anywhere the linker could see. And an error while running means the program was built but did something wrong. Learning to tell these three apart is one of the first professional skills.

main.cpputil.cpppreprocess+compilepreprocess+compilemain.outil.olink→ executable
One command, three steps: the preprocessor and compiler work on each source file separately, and the linker joins the results.
ComputationC

Installing a compiler and running a first program

You need one of the three major compilers. All are free.

  • Linux: install GCC from your distribution (sudo apt install g++ on Debian and Ubuntu, sudo dnf install gcc-c++ on Fedora). Clang is usually one package away.
  • macOS: run xcode-select --install to get Apple's Clang. For the newest C++23 library features, Homebrew's llvm or gcc packages are often ahead of Apple's.
  • Windows: install Visual Studio Community with the Desktop development with C++ workload, which gives you MSVC and an IDE; or use GCC through MSYS2 or WSL.

Check what you have with g++ --version or clang++ --version. For this course you want GCC 14 or later, Clang 18 or later, or a current Visual Studio 2022 or newer, because the lessons use C++23's std::println.

Here is the first program. Save it as main.cpp:

cpp
#include <print>

int main() {
    std::println("Hello, world!");
    std::println("{} + {} = {}", 2, 3, 2 + 3);
}

Compile and run it:

bash
g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o main
./main

It prints:

text
Hello, world!
2 + 3 = 5

Each flag matters. -std=c++23 chooses the language version (compilers default to an older one). -Wall -Wextra turn on warnings, which catch real bugs; professionals compile with warnings on and treat new ones as problems to fix. -O2 asks for optimisation, and -o main names the output. With Clang the command is the same with clang++; with MSVC, from a Developer Command Prompt, it is cl /std:c++latest /EHsc /W4 main.cpp.

std::println takes a format string in which each {} is replaced by the next argument, then ends the line. It is new in C++23 and is based on the C++20 std::format library, which in turn grew out of the open-source {fmt} library. You can put a format specification after a colon inside the braces: alignment, width and precision. The next program uses them to print a small table.

cpp
#include <iostream>
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> cities{"Accra", "Lima", "Hanoi", "Tromsø"};
    std::vector<double> rain_mm{12.0, 0.5, 48.5, 21.0};

    double total = 0.0;
    for (std::size_t i = 0; i < cities.size(); ++i) {
        std::println("{:<8} {:>8.1f} mm", cities[i], rain_mm[i]);
        total += rain_mm[i];
    }
    std::println("average  {:>8.1f} mm", total / rain_mm.size());

    // The older way, still everywhere in existing code:
    std::cout << "cities: " << cities.size() << '\n';
}
text
Accra        12.0 mm
Lima          0.5 mm
Hanoi        48.5 mm
Tromsø       21.0 mm
average      20.5 mm
cities: 4

(The rainfall figures are invented for the example: one week at four imaginary weather stations.)

ExplanationH

Reading the program line by line

#include <iostream>, <print>, <string>, <vector>. Each line makes part of the standard library visible. In C++ you include what you use; forgetting an include sometimes still compiles, because another header happened to include it for you, and then breaks on a different compiler. Include every header whose names you use.

std::vector<std::string> cities{...}; declares a variable named cities. Its type is std::vector<std::string>: a growable array (a vector) whose elements are strings. The angle brackets give the element type; that is a template, which you will write yourself in a later lesson. The braces hold the initial elements. Braces are the modern, uniform way to initialise almost anything.

double total = 0.0; is a 64-bit floating-point variable on every mainstream platform. Unlike Python, every variable in C++ has a type fixed at compile time, and the compiler checks every use of it.

for (std::size_t i = 0; i < cities.size(); ++i) is the classic three-part loop: start, condition, step. std::size_t is the unsigned integer type used for sizes and indices. ++i adds one. In the next lessons you will mostly use the simpler range-for, for (const auto& city : cities), which visits each element without an index.

"{:<8} {:>8.1f} mm": <8 means "left-align in 8 columns", >8.1f means "right-align in 8 columns, fixed-point with 1 decimal". Notice that Tromsø lined up even though ø takes two bytes in UTF-8: the formatting library estimates how wide text looks, not how many bytes it has.

std::cout << ... << '\n'; is the stream output that C++ used for thirty years before std::println. The << operator sends each value to the stream in turn. You will meet it in nearly every existing codebase, so you should read it fluently, but for new code std::println is shorter, its format string is checked at compile time, and it is often faster.

Here is a third program that shows off a little more of the library: it counts words in a sentence with std::map, which keeps its keys sorted, and finds the most common word with a standard algorithm.

cpp
#include <algorithm>
#include <map>
#include <print>
#include <sstream>
#include <string>

int main() {
    const std::string text = "the cat saw the dog and the dog saw the cat run";

    std::map<std::string, int> counts;   // keeps its keys sorted
    std::istringstream words(text);
    for (std::string w; words >> w;) {
        ++counts[w];
    }

    for (const auto& [word, n] : counts) {
        std::println("{:>4} {}", word, n);
    }

    auto most = std::ranges::max_element(counts, {}, [](const auto& kv) { return kv.second; });
    std::println("most common: '{}' ({} times)", most->first, most->second);
}
text
 and 1
 cat 2
 dog 2
 run 1
 saw 2
 the 4
most common: 'the' (4 times)

Do not worry about every detail yet. counts[w] creates an entry with value 0 the first time a word is seen, and ++ adds one. const auto& [word, n] unpacks each key-value pair (a structured binding). The [](const auto& kv) { return kv.second; } is a lambda, a small unnamed function, telling max_element to compare entries by their counts. Every one of these gets its own section later in the course.

When the compiler says no

Change one line of a correct program to int year = name;, where name is a std::string, and GCC 14 answers:

text
main.cpp: In function 'int main()':
main.cpp:6:16: error: cannot convert 'std::string' {aka 'std::__cxx11::basic_string<char>'} to 'int' in initialization
    6 |     int year = name;
      |                ^~~~
      |                |
      |                std::string {aka std::__cxx11::basic_string<char>}

Read it in order: the file, the line (6) and column (16); the word error; then a sentence in plain language. The aka part spells out what std::string really is inside the library, which you can usually skip. When a single mistake produces a page of messages, fix the first error and recompile: the later ones are often consequences of it. Template-heavy code can produce famously long messages; C++20 concepts, which you will meet in the Practice level, were designed partly to make them short again.

Common misconceptionsH

Common misconceptions

Misconception

"C++ is just C with classes, so I should learn C first." C++ started that way, but modern C++ is written very differently from C: strings and vectors instead of character arrays and manual malloc, references instead of most pointers, destructors that clean up automatically. Learning C first teaches habits you will then need to unlearn. Learn C when you need it for its own sake.

Misconception

"If it compiles, it works." The compiler checks types, not intentions. Worse, some mistakes, such as reading past the end of an array or using an object after it has been destroyed, are undefined behaviour: the program may print the right answer today and crash tomorrow, or only with optimisation turned on. Warnings, tests and the sanitizers you will meet in the Professional level are how professionals catch them.

Misconception

"You need std::endl to end a line." std::endl writes a newline and forces the output to be flushed, which can make output-heavy programs much slower. Write '\n' with streams, or use std::println, which ends the line for you.

Misconception

"There is one C++." There is one standard, but several compilers and standard libraries implement it, at different speeds. Code that compiles on one compiler can fail on another if it relies on an extension or an accidental include. Projects that must be portable test with at least two compilers.

Further reading

How professionals work, and where to read more

Professional C++ developers keep cppreference.com open all day: it documents every feature and marks the standard that introduced it. They test small ideas on Compiler Explorer, where you can run the same code through GCC, Clang and MSVC side by side and even see the machine code each produces. Larger programs are built with a build system (usually CMake), which you will set up in the last lesson, inside an editor with a language server such as clangd that shows errors as you type.

For the language's own story, Stroustrup's The Design and Evolution of C++ explains the early decisions, and his home page links his papers on the language's history since. The Standard C++ Foundation publishes news from the committee.

Exercises

Exercises

1. First steps with C++

Warm-upHuman

A project has two files, main.cpp and stats.cpp. You build with g++ -std=c++23 main.cpp -o app and get:

undefined reference to `mean(std::vector<double, std::allocator<double> > const&)'

Which step failed, and what is the most likely cause?

Choose one

2. First steps with C++

Warm-upComputational

What does this program print? Type the line exactly, including the brackets.

#include <print>

int main() {
    std::println("[{:>5}|{:<3}|{:^7}]", 42, 7, "mid");
}

3. First steps with C++

Warm-upComputational

What does this program print?

#include <print>

int main() {
    std::println("{} {} {}", 7 / 2, 7 % 2, 7.0 / 2);
}

4. First steps with C++

CoreComputational

What number does this program print?

#include <print>

int main() {
    int count = 0;
    for (int i = 1; i < 20; i *= 3) {
        ++count;
    }
    std::println("{}", count);
}

5. First steps with C++

CoreComputational

What does this program print?

#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"Ngozi", "Aiko", "Mateus"};
    names.push_back("Leila");
    std::string longest;
    for (const auto& n : names) {
        if (n.size() > longest.size()) longest = n;
    }
    std::println("{} {}", names.size(), longest);
}

6. First steps with C++

CoreHuman

Which of these follow from C++'s zero-overhead principle? Select all that apply.

Choose all that apply

7. First steps with C++

Warm-upHuman

In which year did C++ first become an ISO international standard?

Further reading and resources

  • C++ compiler support · cppreference.comWhich compiler version supports which C++20, C++23 and C++26 feature.
  • std::print and std::println · cppreference.comThe C++23 printing functions used throughout this course.
  • C++ Standards Support in GCC · GCC project
  • Compiler ExplorerPaste any program from this course, pick a compiler, and run it in your browser.
  • The Design and Evolution of C++ · Bjarne Stroustrup · 1994The designer's own account of the decisions behind the language, written before the first ISO standard.