C++ 101: The Language That Trusts You Completely
C++ gives you control over every byte of memory, and its modern features do most of the cleanup for you. Values, references, RAII, classes, templates and the standard library, with the reason behind each one.

C++ began in 1979 as "C with Classes". Bjarne Stroustrup wanted to keep the speed of C and add the classes of Simula, an older language made for simulations. Today C++ runs inside web browsers, game engines, databases, trading systems, and most of the machine learning libraries that Python calls.

One design rule has held the whole time. It's called the zero-overhead principle.
You don't pay for what you don't use, and what you do use, you could not hand code any faster.
This rule explains both sides of the language's reputation. C++ is fast because it adds no hidden work. People call it dangerous for the same reason, because it adds no hidden checks either. The language assumes you know what you are doing, and it doesn't stop you.
The C++ many of us learned in school was the 1990s style, with long chains of classes inheriting from each other and memory freed by hand. Most of that is outdated now. This post covers modern C++, the way it's written today, with the reason behind each piece.
Hello, compilation
#include <iostream>
int main() {
std::cout << "hello, world\n";
return 0;
}
To compile it, run g++ -std=c++20 -Wall hello.cpp -o hello. The -std=c++20 part picks the 2020 version of the language, and -Wall turns on most warnings.
C++ builds a program in two steps, and you deal with both of them directly. First the compiler turns each .cpp file into an object file, one file at a time. Then the linker joins the object files into one program.
The #include line copies the text of another file into yours before compiling. That's why C++ has header files (.h). They hold the declarations that several .cpp files need. In a large project there are too many of these files to manage by hand, so projects use a build system such as CMake. C++20 added modules to replace #include, but most code you read will use #include for years to come.
std:: is the namespace of the standard library. A namespace is a prefix that keeps the library's names apart from yours. Tutorials often write using namespace std; so that they can leave the prefix out. That's fine in a small test file. In a header it causes problems, because it pulls thousands of names into every file that includes the header.
Values, and where they live
The most important idea in C++ is that every variable is an object at a real address in memory, and you decide where that memory is.
int x = 42; // stack: automatic, freed when the scope ends
int* p = new int(42); // heap: manual, lives until you delete it
x lives on the stack, and it's freed automatically when the block it's in ends. The 42 that p points to lives on the heap, and it stays there until you free it yourself with delete.
A function can receive an argument in three ways.
void byValue(std::string s); // gets its own copy
void byRef(std::string& s); // uses the caller's string, can change it
void byConstRef(const std::string& s); // uses the caller's string, read only
Passing by value makes a copy. If the argument is a vector of a million numbers, all million are copied. Passing by reference doesn't copy anything. The function gets an alias, which is a second name for the caller's own string. Adding const means the function can read the string but not change it.
So the usual rule is this. Pass small types such as int and double by value, because copying them costs almost nothing. Pass anything larger as const T&.
A reference, like std::string& s, is always connected to one object. It can't be empty, and it can't be switched to a different object later. A pointer, like std::string* p, holds an address. It can be null, which means it points to nothing, and it can be changed to point somewhere else. Use a reference by default. Use a pointer only when the object might not exist, or when you need to point at a different object later.
The stack and heap diagram above mentions undefined behaviour, which is the best known danger in C++. It means the language makes no promise at all about what happens. Reading past the end of a vector is one example.
std::vector<int> v = {1, 2, 3};
int a = v[10]; // undefined behaviour: no check, anything can happen
int b = v.at(10); // checked: throws std::out_of_range
v[10] might crash, return a random number, or seem to work for a long time. The compiler assumes your program never does this, and it builds the program on that assumption. Using memory after it was freed and overflowing a signed integer are undefined behaviour too. This is the cost of the zero-overhead principle. C++ doesn't add a check unless you ask for one, the way at() does.
RAII: the best idea in the language
This section covers the idea that makes the rest of modern C++ work.
When a block of code ends, the objects created inside it are destroyed right away, in a known order. Destroying an object runs a special function called its destructor. C++ uses this to clean up every kind of resource automatically, such as an open file, a lock or a piece of memory.
{
std::ifstream file("config.json"); // constructor opens the file
std::lock_guard lock(mutex); // constructor takes the lock
auto data = parse(file);
// ...
} // scope ends: destructors run in reverse order, always.
// lock released, file closed, even if parse() threw an exception.
This is called RAII, short for Resource Acquisition Is Initialization. The name is confusing, but the idea is short. The constructor takes the resource, and the destructor gives it back. The destructor always runs when the block ends, so the cleanup can't be forgotten. That's also true when the function returns early or when an error is thrown.
Other languages ask you to write the cleanup yourself. Java and Python have finally blocks, and Go has defer. In C++ the type does the cleanup for you.
The standard library uses RAII everywhere. std::string frees its text, std::vector frees its elements, std::ofstream writes out and closes its file, and std::lock_guard releases its lock. Most of modern C++ is about making every resource work this way. The next section does the same for memory.
Smart pointers: new and delete are for library authors
Memory taken with new has to be given back with delete. If you forget, the memory leaks, which means it stays in use until the program ends. If you call delete twice on the same memory, that's undefined behaviour. Modern C++ avoids both problems by putting heap memory inside RAII types called smart pointers.
auto p = std::make_unique<Circle>(2.0); // sole owner, freed when p dies
auto q = std::make_shared<Circle>(3.0); // reference counted
unique_ptr is the one to use by default. It has exactly one owner, and it's as fast as a plain pointer. It can't be copied, because a copy would mean two owners. It can only be moved, which hands the ownership to someone else.
shared_ptr lets several owners share one object. It keeps a count of its owners and frees the object when the count reaches zero. Keeping that count costs a little time, and real programs need shared ownership less often than it first seems.
The modern rule is short.
Application code shouldn't need
delete. Ownership belongs in types, not in what you remember about the codebase.
Plain pointers are still used, but only with one meaning: "I can use this object, but I don't own it, so I don't free it."
Classes: construction, copying, and moving
class Circle {
public:
explicit Circle(double r) : radius_(r) {}
double area() const { return 3.14159265 * radius_ * radius_; }
private:
double radius_;
};
Here is what each part does.
- Members of a
classare private by default. Astructis the same thing, except that its members are public by default. - The
constafterarea()promises that the method doesn't change the object. explicitstops the compiler from turning adoubleinto aCircleon its own. Without it, passing2.0where aCircleis expected would quietly create one. This is one of several places in C++ where the risky behaviour is the default and you have to turn it off.
The bigger question is what happens when an object is copied. C++ objects are values, so assigning one object to another copies its contents. For a vector of a million numbers, that's a lot of work.
C++11 added move semantics to avoid that work.
std::vector<double> a = makeBigVector();
auto b = a; // COPY: allocate and duplicate a million doubles
auto c = std::move(a); // MOVE: c steals a's internal buffer. Three
// pointers change hands and a is left empty.
A move hands over the data inside an object instead of copying it. Most of the time you don't write std::move yourself. When a function returns a local variable, C++ moves it automatically, or skips the copy completely.
This is why C++ containers are cheap to return from a function and cheap to pass along. They only cost a full copy when you really ask for a second copy. Moving is also how a unique_ptr changes owner, since it can't be copied.
Templates: generics that compile to nothing
A template is code written once for any type. The compiler then writes a separate version of that code for each type you use it with.
template <typename T>
T maxOf(T a, T b) {
return a > b ? a : b;
}
maxOf(3, 7); // compiler generates maxOf<int>
maxOf(2.5, 1.5); // and a separate maxOf<double>
Each generated version is the same code you would have written by hand for that type. Nothing is checked or converted while the program runs, so a template costs nothing at run time. That's the zero-overhead principle again.
The cost is paid while compiling instead. Builds take longer, and the error messages used to be very long. A typo deep inside a template could produce two hundred lines of errors. C++20 added concepts, which let you state what a type must support. If a type doesn't fit, you get a short error that says why.
template <std::integral T> // clear requirement, clear error if violated
T half(T x) { return x / 2; }
The STL: containers, iterators, and algorithms
The STL (Standard Template Library) is the part of the standard library that is built from templates. It has three kinds of parts.
- Containers hold data.
std::vectoris one. - Algorithms work on data.
std::sortis one. - Iterators connect the two. An iterator points at one element and can step to the next one.
Every algorithm is written against iterators, not against one particular container. So std::sort works on any container that can hand it iterators. With 10 algorithms and 10 containers, the library needs 20 pieces of code instead of 100.
std::vector<int> v = {5, 3, 1, 4, 2}; // the default container
std::sort(v.begin(), v.end());
for (int x : v) std::cout << x << ' '; // 1 2 3 4 5
std::unordered_map<std::string, int> ages{{"ada", 36}, {"linus", 55}};
ages["grace"] = 85;
Use std::vector unless you have measured a reason to use something else. Its elements sit next to each other in memory, and the CPU loads memory into its cache 64 bytes at a time, so the next element is usually already there. Because of that, a vector is faster than a linked list at most real sizes, even for operations where a linked list should win on paper.
A few more types you will see often. std::string holds text. std::unordered_map is a hash table, which finds a value by its key. std::optional<T> holds either a value or nothing, and C++ uses it where Go would return a value and an ok flag.
Since C++20, ranges let you chain algorithms without writing begin() and end() each time.
auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });
The [](int x) { ... } part is a lambda, which is a small function without a name, written right where it's used. Modern STL code uses lambdas everywhere.
Errors: exceptions, mostly
C++ handles errors the opposite way from Go. A function that fails throws an exception. The exception travels back through the functions that called it until it reaches a catch. Every function it passes through on the way has its objects destroyed, so their destructors run. That's why RAII and exceptions work well together. Nothing is left open.
try {
auto config = loadConfig("config.json"); // may throw
} catch (const std::exception& e) {
std::cerr << "failed: " << e.what() << '\n';
}
In practice, C++ projects don't all agree on this. Game engines, and codebases that follow Google's style guide, often turn exceptions off because their cost is hard to predict. They return error codes instead, or C++23's std::expected, which holds either a value or an error. When you start reading a C++ codebase, check which of these it uses.
The dialect problem, and the way through
C++ never removes old features. C-style arrays, raw new, char* strings, 1990s class hierarchies, C++11 move semantics and C++20 concepts all still compile today, sometimes in the same file.
So C++ is really a family of styles, and each codebase picks one. Here is what I'd do as a learner.
- Write modern C++ from day one. Use
auto, range-basedforloops, smart pointers, STL containers and lambdas. Treat rawnew,deleteand C-style arrays as outdated. - Turn on the compiler's checks. Always use
-Wall -Wextra. In debug builds, add-fsanitize=address,undefined. These sanitizers watch the program while it runs and catch the memory mistakes that the language itself doesn't. - Read the C++ Core Guidelines. They are the closest thing to an official answer about which style to write, and Stroustrup edits them himself, together with Herb Sutter.

Next Steps
A Tour of C++ by Stroustrup is short, it covers modern C++, and it's the right first book. cppreference.com is the reference you will use every day. Compiler Explorer shows the machine code that your C++ turns into.
A good first project is a command-line tool that reads a file into a vector of structs and answers questions about the data. It's small enough to finish, and it makes you use ownership, references and the STL properly.
To sum up, C++ gives you full control over the machine. Its modern features cost nothing at run time and clean up after themselves, as long as you follow the modern habits. The language trusts you completely, and those habits mean you rarely need that trust.
Check yourself
3 questions · nothing is savedReferences & Primary Sources
Official specifications, standards, and documentation cited in this post.
- [1]
The international standard defining modern C++20 language features, memory model, and standard library.
STANDARDiso.org - [2]
Authored by Bjarne Stroustrup and Herb Sutter, guiding modern idiomatic C++, RAII, and type safety.
DOCSisocpp.github.io - [3]
Authoritative community reference documentation for C++ standard library, templates, and STL algorithms.
DOCSen.cppreference.com
- Written
- Feb 5, 2026
- Length
- 2,501 words · 11 min
- Built
- …
- Served by
- …
- Delivered
- …
- Over the wire
- …
- Go's share
- …
Go 101: A Small Language for Big Systems
Go has very few features, and that's on purpose. Types, slices, interfaces, errors and goroutines: the core of the language in one post, with the reason behind each design choice.
- 1C++ 101: The Language That Trusts You Completely
- 2Go 101: A Small Language for Big Systems
- 3The Two Jobs of the Asterisk: Pointers in Go and C++
- 4List* l or List *l? The Oldest Style War in Programming
- 5From C++ to Go: Demystifying Pointers, Slices, and Errors
- 6Why Go Rewrites 0644 as 0o644 (and Why chmod Won't Take 'rwx')
OpenCV 5: What Actually Changed Under the Hood
The first major version since 2018 is about foundations, not new features: a rebuilt engine that runs over 80% of ONNX instead of 22%, real n-dimensional arrays, fast code from four chip makers, and a list of removals long enough to break your build.
OpenCV 101: Every Image Is a Grid of Numbers
A photo is a rectangle of numbers, and everything OpenCV does is arithmetic on that rectangle. Mat, BGR, convolution, thresholds, contours and perspective warps: the ideas that make the library's 2,500 functions easier to find your way around.
Memory: The Stack, the Heap, and Pointers
Where your variables actually live, why the heap costs more than the stack, and what a pointer really is.
