C++ Tutorial for Beginners
Learn C++ programming step by step, from your first program to classes, the STL, smart pointers and templates, with modern C++ examples, exercises and quizzes for beginners.
Browse all 44 lessons by stage
- Lessons
- 44
- Code examples
- 94
- Exercises
- 144
- Quiz questions
- 163
C++ course at a glance
Who it's for
Complete beginners ready for a challenge, computer science students, aspiring game and systems developers, and programmers who want to understand how software uses memory.
Prerequisites
None for the core lessons, though patience helps: C++ is large. The in-depth guides list the lessons to finish before you start them.
What you need
A C++20 compiler (GCC, Clang or Microsoft Visual C++) and an editor such as VS Code, Visual Studio Community or CLion. An online compiler works for the first lessons.
How long it takes
About three months for the 25 core lessons at five hours a week. Mastering C++ takes years, but the core lessons get you writing useful programs.
C++ roadmap: beginner to advanced
Work through the 25 core chapters in the first three stages in order, then use the reference stages to go deeper. Each reference lesson links to its prerequisite and includes examples, practice and a quiz.
Beginner
Your first program, variables, operators, strings, decisions, loops, functions and vectors.
- 1IntroductionWhat C++ is, how to install a compiler, and how a Hello World program works line by line.
- 2Variables & InputStore values in typed variables, use strings and constants, and read user input with cin.
Show all 8 lessonsShow fewer
- 3Operators & MathCalculate in C++ with arithmetic operators, integer division and remainder, increment and compound assignment, static_cast, the cmath library and random numbers.
- 4StringsWork with text using std::string: length, indexing, substr, find, replace, comparing, joining and converting to and from numbers.
- 5if / elseMake decisions with comparisons, if, else if, else, logical operators, the ternary operator and switch.
- 6LoopsRepeat code with for, while and do-while loops, and stop or skip passes with break and continue.
- 7FunctionsSplit programs into reusable functions with parameters, return types, default values and references.
- 8Arrays & VectorsStore many values in arrays and std::vector, access them by index and loop through them.
Intermediate
Recursion, formatting, structs, pointers, classes, STL containers and algorithms, exceptions and files.
- 9RecursionSolve problems with functions that call themselves: base and recursive cases, the call stack, recursion versus loops, and classic examples like factorial, binary search and folder sizes.
- 10Formatting & StreamsControl how numbers and text appear with iomanip: decimal places, column widths, alignment and fill characters, then build and parse strings with stringstream.
Show all 9 lessonsShow fewer
- 11Structs & EnumsGroup related values into structs, store them in vectors, pass them to functions and name fixed options with enum class.
- 12PointersUnderstand memory addresses, pointers, dereferencing, nullptr, the arrow operator and how pointers relate to arrays and references.
- 13Classes & ObjectsBuild classes with private data, public member functions, constructors, const methods and destructors.
- 14Maps & Sets (STL)Store key-value pairs with std::map and unordered_map, keep unique values with std::set, and use STL algorithms like sort and find.
- 15Algorithms & LambdasReplace hand-written loops with standard algorithms such as sort, find_if, count_if, accumulate and transform, customised with lambda expressions.
- 16ExceptionsHandle errors with try, catch and throw, use the standard exception types, write your own exception class, and understand how RAII keeps programs safe when errors happen.
- 17Files (fstream)Write and read text files with ofstream and ifstream, process files line by line, parse CSV data and check for errors.
Advanced
Inheritance, operator overloading, project structure, smart pointers, move semantics, templates, optional, variant and threads.
- 18Inheritance & PolymorphismBuild derived classes, call base constructors, override virtual functions and use polymorphism through base-class pointers.
- 19Operator OverloadingMake your own types work with +, -, ==, <, << and [] by overloading operators, as member or non-member functions, following the rules that keep them predictable.
Show all 8 lessonsShow fewer
- 20Headers, Files & CMakeSplit a program into header and source files, prevent double inclusion, group code in namespaces, and build projects with g++ and CMake.
- 21Smart PointersUnderstand stack and heap memory, why raw new and delete are risky, and how unique_ptr and shared_ptr manage memory for you.
- 22Move SemanticsAvoid expensive copies by moving resources instead: copying versus moving, std::move, rvalue references, move constructors, emplace_back and the rule of zero and five.
- 23TemplatesWrite code once for many types with function and class templates, and see how the STL is built on them.
- 24optional & variantExpress "maybe a value" with std::optional and "one of several types" with std::variant, and handle them safely with value_or, holds_alternative and std::visit.
- 25Threads & ConcurrencyRun work in parallel with std::thread, protect shared data with mutex and atomic, avoid data races, and get results back with std::async and futures.
Language and standard library
Namespaces, const, casts, arrays and span, string_view, iterators, containers, queues, hashing, chrono, random, friends, multiple inheritance and special members.
- 26Scope and LinkageDistinguish C++ scope, lifetime and linkage, organize names with namespaces, hide translation-unit helpers, and expose consistent declarations across files.
- 27Const CorrectnessDesign const-correct C++ interfaces, distinguish pointer qualifiers, overload read access safely, and avoid casting away genuine immutability.
Show all 14 lessonsShow fewer
- 28Casts and Numeric SafetyCheck C++ numeric ranges before narrowing, prevent signed overflow, parse integers with from_chars, and distinguish cast notation from runtime validation.
- 29Array and SpanUse std::array and C++20 std::span to separate ownership from views, preserve extent information, and map a checked two-dimensional grid to flat storage.
- 30String View LifetimesUse C++17 string_view for borrowed text, keep its owner alive, distinguish views from copies, and avoid null-termination and temporary-lifetime mistakes.
- 31Iterator InvalidationTrack C++ iterator, pointer and reference validity during mutation, erase safely, and reacquire vector elements by stable identifiers instead of stale handles.
- 32List and DequeChoose C++ list or deque from actual operations, understand traversal and storage tradeoffs, move list nodes with splice, and avoid invalidation assumptions.
- 33Container AdaptorsUse C++ container adaptors for LIFO, FIFO and priority workflows, check empty access, design strict comparators, and define deterministic priority ties.
- 34Unordered ContainersUse C++ unordered maps and sets with compatible equality and hashing, distinguish iterator rehash rules, and sort output when deterministic ordering matters.
- 35Chrono and DatesChoose C++ chrono clocks by purpose, convert duration units explicitly, validate C++20 calendar dates, and test deadline rules without sleeping.
- 36Random GenerationSeparate C++ random engines from distributions, seed deliberately, test repeatability across stated environments, and sample without replacement.
- 37Friend AccessGrant deliberate C++ friend access, distinguish friendship from membership and inheritance, and preserve invariants through narrow collaborators.
- 38Multiple InheritanceUse C++ multiple inheritance for interfaces, understand diamond subobjects, initialize shared virtual bases, and recognize when composition is clearer.
- 39Special Members and GuaranteesDesign coherent C++ copy and move operations, maintain moved-from invariants, use noexcept honestly, and implement changes with a strong exception guarantee.
Templates and ranges
Template deduction, specialisation and parameter packs, concepts and requires clauses, and lazy pipelines with ranges and views.
- 40Advanced TemplatesPredict C++ template deduction, distinguish overloads and specializations, expand packs with C++17 folds, and keep generic contracts focused.
- 41Concepts and RequiresUse C++20 concepts and requires expressions to state template capabilities, reject unsupported calls clearly, and separate type checks from semantic rules.
Build and quality tools
Debugging and testing with sanitizers, and organising reproducible builds with CMake targets.
- 43Debugging and TestingBuild C++ regression checks, inspect state with a debugger, use supported sanitizers, and distinguish undefined behavior from ordinary validation failures.
- 44CMake and BuildsBuild C++ libraries and apps with CMake targets, propagate usage requirements, distinguish build configurations, share presets, and run CTest checks.
What is C++?
C++ is a programming language built for speed and control. It runs the engines of video games, web browsers like Chrome, operating systems, music software, self-driving car systems and trading platforms: anywhere that every millisecond and every byte of memory matters.
C++ is a compiled language. A compiler turns your code into a program made of instructions the processor understands directly, which is why C++ programs are so fast. It's also statically typed, like Java: every variable has a declared type that the compiler checks.
This tutorial teaches modern C++ in three stages. The beginner stage covers compiling your first program, variables and input, operators and maths, strings, decisions, loops, functions and vectors. The intermediate stage introduces recursion, output formatting and string streams, structs and enums, pointers, classes, the STL's maps, sets and algorithms with lambdas, exceptions and files. The advanced stage covers inheritance and polymorphism, operator overloading, organising projects with headers and CMake, smart pointers, move semantics, templates, optional and variant, and threads: the tools real C++ projects are built with.
C++ has a reputation for being difficult because it's a very large language. You don't need all of it to start. Each lesson focuses on the parts that matter most, with the exact output of every example.
How to follow this course
Work through the 25 core lessons in order, because each one builds on the last. After that, the in-depth guides answer the questions real C++ projects raise. The language and standard library guides cover namespaces and linkage, const correctness, casts, arrays and std::span, string_view lifetimes, iterator invalidation, choosing containers, queues, hashing, <chrono>, random numbers, friends, multiple inheritance and the special member functions. The templates and ranges guides cover deduction and parameter packs, concepts and ranges. The build and quality guides cover debugging with sanitizers and CMake targets. Each guide lists the core lessons to finish first.
What you will learn
10 practical skills, built one lesson at a time
- Install a compiler and build and run C++ programs
- Calculate with operators and format output with iomanip
- Control programs with if/else, switch, loops and recursion
- Write functions and store data in vectors, structs and enums
- Understand pointers, references and memory
- Design classes with constructors, encapsulation, inheritance and overloaded operators
- Use STL containers and algorithms with lambdas
- Handle errors with exceptions and read and write files
- Split projects into headers and source files and build them with CMake
- Use smart pointers, move semantics, templates, optional, variant and threads
Practise C++ your way
Learning sticks when you use it. Pick a mode.
C++ Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
144 exercisesC++ Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
163 questionsC++ Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where C++ fits in a complete roadmap, and what to learn next.
View learning pathsC++ FAQ
Is C++ good for beginners?
C++ asks you to think about details other languages hide, such as exact types and memory, which makes the first steps a little slower. In return you learn how computers really work, and every other language feels easier afterwards. Keeping to the modern style, as this course does, makes it very approachable.
What's the difference between C and C++?
C++ started as "C with classes". It keeps almost everything from C and adds features such as classes, strings, vectors, templates and a large standard library. Modern C++ code looks quite different from C and is usually safer and easier to write.
Which compiler should I use?
On Windows, Visual Studio Community includes the MSVC compiler, or you can install g++ through MSYS2. On macOS, install Xcode's command line tools to get clang. On Linux, g++ is usually one command away. The first lesson shows how to compile and run code.
How long does it take to learn C++?
With about an hour a day, most learners finish the beginner stage in two weeks and the full course in about four months. Becoming truly fluent takes longer, because C++ is a large language, but these lessons cover what you need for games, competitive programming and most entry-level work.
What can I build with C++?
Games with Unreal Engine, desktop apps, embedded programs for devices like Arduino, high-performance tools and parts of other languages and browsers. It's also popular in competitive programming.
Is this C++ course free?
Yes. All 25 core lessons, the 19 in-depth guides, the exercises, the quiz and the cheat sheet are free, with no account or sign-up needed.
Which C++ standard does the course use?
The course teaches modern C++, with examples written for C++20. Features such as std::format, concepts and ranges need C++20, so set your compiler to -std=c++20 or later; some in-depth guides only need C++17 and say so at the start.
Should I learn C before C++?
No. Modern C++ is best learned directly: strings, vectors and smart pointers replace much of the manual memory handling that C requires. Learning C later is easy once you know C++.
Is C++ still worth learning?
Yes. C++ remains a leading language for game engines, browsers, databases, embedded systems, finance and high-performance computing, and it receives a new standard every three years.
More tutorials
Python
A friendly first programming language for scripts, data and automation.
Start PythonJava
A reliable, widely used language for apps, Android and big systems.
Start JavaKotlin
The modern language for Android apps, servers and multiplatform code.
Start KotlinSwift
Apple's fast, safe language for iPhone, iPad, Mac and SwiftUI apps.
Start SwiftC#
Microsoft's versatile language for web APIs, games with Unity and desktop apps.
Start C#PHP
The server-side language behind WordPress and millions of websites.
Start PHP