C++ guides
Modern C++ guides: C++20 and C++23 features, compilers, build systems, and measured performance.
-
Fix C++ "request for member in pointer type" — Use -> on Pointers, and Why -> Cannot Fix a Non-Class Type
The GCC error request for member in a pointer type means the dot operator was used on a pointer: dot requires an object of class type, arrow requires a pointer to class type and is exactly equivalent to dereferencing first. This guide reproduces the dot-on-pointer failure and GCC's maybe you meant to use '->' suggestion, fixes it with the arrow and with the parenthesized dereference form, shows why the unparenthesized star form fails on precedence, covers the sibling non-class type error where the pointee has no members and arrow does not help, and ends with references and std::unique_ptr, where dot and arrow both compile but reach different objects.
-
Fix C++ "no match for 'operator<<'" — Streaming a User-Defined Type and a std::vector of It to std::cout
Streaming a user-defined type to std::cout fails with no match for 'operator<<' because std::basic_ostream provides overloads only for built-in types, character data, and a few library types. This guide reads the exact GCC error, fixes it with a non-member operator<< taking (std::ostream&, const T&) and returning std::ostream& so chaining works, shows the friend-defined-inside-class form for private members, adds a separate overload for a std::vector of the type, and shows why a non-const reference parameter breaks streaming of const objects.
-
Fix C++ "invalid conversion from 'const char*' to 'char*'" — Add const, Copy the Text, or Own It in std::string
The GCC error invalid conversion from 'const char*' to 'char*' means read-only text was handed to code that claims the right to modify it: a string literal, a const char* variable, or the result of c_str() was assigned to a char* or passed to a char* parameter. This guide reproduces the error in all three forms, explains why GCC reports the literal form with different wording and only as a warning by default, and gives the four correct fixes in order: declare const char* when nothing writes, copy into a local char array when a callee really writes, store the text in std::string and use data() when it must be owned and mutable, and reserve const_cast for the one narrow legacy case where the underlying object is genuinely mutable.
-
Fix C++ "'cout' was not declared in this scope" — Missing
, Missing std::, and the using namespace std Trade-Off The error 'cout' was not declared in this scope has two different causes with the same first line: no
included at all, or included but cout used without std:: qualification, because std::cout lives in namespace std and its name is not injected into the global scope. This guide reproduces both failures with GCC, reads the did-you-mean suggestion that only the second failure earns, fixes both with std::cout, covers std::endl versus a newline character, shows the using namespace std form and why it stays out of headers, and ends with the wrong-header trap where provides std::printf but not std::cout. -
Fix C++ "cannot convert 'std::string' to 'const char*'" — c_str(), data(), and When the API Wants char*
Passing a std::string where a const char* is expected fails because there is no implicit conversion from std::string to a character pointer. This guide reads the exact GCC error at a real std::fopen call, fixes it with c_str() for read-only APIs, shows why c_str() still fails for a char* parameter while data() on a non-const string works since C++17, and states the invalidation rule that ends the useful life of every pointer these functions return.
-
Fix 'No Matching Function for Call' in C++ — Reading GCC's Candidate List, Viable vs Not Viable, and Conversion Failures
The error means overload resolution found candidates for the name but none of them was viable for the arguments given. This guide reads three real GCC failures candidate by candidate — a std::string offered to print(int) and print(const char*), a two-argument call against one-parameter overloads, and a template whose two parameters deduce conflicting types for T — then fixes each one at the coordinate its candidate note names: add the missing overload, call .c_str() for the pointer overload, match the argument count, or state the template argument explicitly.
-
Fix 'Invalid Use of Incomplete Type' in C++ — Forward Declarations, sizeof, and the Pimpl Trap
The error means the compiler met a use that needs a type's size or members at a point where only a forward declaration has been seen. This guide reads three real GCC failures clause by clause: member access and sizeof on a forward-declared struct, a std::unique_ptr pimpl whose destructor is defaulted where the implementation type is still incomplete, and a forward-declared base class. It also shows the nearby case that is not this error at all, deleting an incomplete type, which compiles with a warning and undefined behavior instead.
-
Fix 'Passing const as this Argument Discards Qualifiers' in C++ — Const Objects, Const References, and Const Methods
The error means a non-const member function was called on an object the compiler must treat as const. This guide reads three real GCC failures — a non-const method on a const object, the same call through a const reference parameter, and a const method that tries to call a non-const helper — then fixes each one at the qualifier that was discarded: make the method const, use mutable only for genuinely internal state, and take a non-const reference only when mutation is the point.
-
Fix a Dangling std::string_view — Lifetime Rules for Views and References to Temporaries
A std::string_view taken from a temporary std::string keeps the address and the length after the temporary is destroyed at the end of the statement: the size still reads 40, the text is corrupted or silently becomes another string's text, and AddressSanitizer reports heap-use-after-free with the fault at the print and the free at the assignment. A reference returned from a temporary fails the other way, with a compiler warning and a segfault. This guide reads the report line by line, states the lifetime rule both programs broke, and fixes the code by owning the string at the layer that outlives the view.
-
Read a C++20 Concepts Error — "Constraints Not Satisfied", Clause by Clause
A GCC concepts failure looks long because it prints the whole chain from the call site to the one atomic constraint that evaluated to false. This guide reads three real diagnostics clause by clause: a std::integral check failed by a double, a std::signed_integral check where an unsigned int passes the first clause and fails only the second, and a custom concept whose requires-expression names the invalid operation. Clang's shorter wording for the same three failures is shown alongside, and the fixed program passes the same types the diagnostics asked for.
-
Fix 'Cannot Bind Non-const Lvalue Reference to an Rvalue' in C++ — Temporaries, Function Arguments, and const&
The error means a non-const lvalue reference was offered a temporary: a literal, an arithmetic result, or any other rvalue that has no lasting name to mutate. This guide reads two real GCC failures clause by clause — binding int& to 42 directly, and passing temporaries to a function taking int& — then shows the two bindings that do accept a temporary, const int& with lifetime extension and int&&, and fixes each call by matching the parameter to the intent: const& for reading, a named lvalue for mutation, and an rvalue reference with std::move for taking ownership.
-
Fix 'Call of Overloaded Function Is Ambiguous' in C++ — Equally Good Conversions, and How Overload Ranking Breaks the Tie
The error means overload resolution found two or more viable functions and none of them was better than all the others. This guide reads three real GCC failures rank by rank — an int offered to print(long) and print(double), a two-argument call where each overload wins one argument and loses the other, and a class whose two conversion functions lead to different overloads — then fixes each one at the coordinate that was tied: add the exact-match overload, change one argument so one candidate wins outright, or state the intended conversion explicitly.
-
Fix C++ "Use of Deleted Function" — Copying a unique_ptr Holder, Deleted Copies, and Deleted Overloads
GCC stops the build with 'use of deleted function' when a copy, a call, or an overload lands on a function the program must not use. This guide reproduces the message exactly as GCC 13.3.0 prints it for four shapes: a class holding a std::unique_ptr whose copy constructor is implicitly deleted, a copy constructor deleted with = delete, a std::unique_ptr passed by value, and an overload set where the deleted overload is the best match — and gives the fix that belongs to each shape: std::move, a clone, a const reference, and removing the deleted overload or converting the argument.
-
Fix C++ shared_ptr Cycle Leak — Two Objects Keep Each Other Alive, weak_ptr Breaks the Cycle
Two objects that hold std::shared_ptr to each other never get destroyed: each count stays at 1 after every outside pointer is gone, no destructor runs, and no error appears. This guide reproduces the leak with a Parent and a Child that own each other, proves it with a std::weak_ptr observer that still reports use_count 1 and expired false after the scope ends, and fixes it by making the Child-to-Parent link a std::weak_ptr, after which both destructors run and the observer reports expired true.
-
Fix C++ Deadlock with std::scoped_lock — Two Mutexes, Opposite Order, One Hang
A program that locks two mutexes in opposite order in two threads can hang forever: each thread holds one mutex and waits for the other, and neither wait ever ends. This guide reproduces that hang with two accounts, two mutexes, and a 100 millisecond pause that makes the deadlock happen every run, shows one hung run's output before timeout kills it with status 124, and fixes it twice: once with std::scoped_lock locking both mutexes in one call in both threads, and once by locking in one consistent order everywhere, with the measured exit status for each run.
-
Fix CMake "Generator Does Not Match" and Stale-Cache Errors When Switching Ninja and Make
Reconfiguring an existing build tree with a different generator fails with Error: generator : Unix Makefiles Does not match the generator used previously: Ninja — and a copied or moved build tree fails differently, with The current CMakeCache.txt directory ... is different than the directory ... where CMakeCache.txt was created. Both errors come from what the first configure pinned in CMakeCache.txt: the generator, the source directory, and the compiler. This guide reproduces both errors verbatim, reads the cache entries that cause them, and fixes them the two clean ways — a fresh build directory per generator, and removing CMakeCache.txt and CMakeFiles — plus the --fresh shortcut that performs that removal, and why editing the cache by hand is not a third fix.
-
Fix CMake "Could NOT Find a Package" — and When FetchContent Is the Right Fallback
Configure fails with Could not find a package configuration file provided by "Greet" — even though the Greet library is built and installed, with a GreetConfig.cmake on disk. This guide reads that error line by line: the module-mode paragraph, the two config file names CMake looked for, and the remedy sentence that names both native fixes. It fixes the search the native way first, with CMAKE_PREFIX_PATH and with Greet_DIR, and then shows the FetchContent fallback for the different case where no package config file exists at all, building the dependency from its sources instead.
-
Fix CMake "Cannot Find Source File" and "No SOURCES Given to Target"
Configure fails with two errors — Cannot find source file: src/main.cpp, and No SOURCES given to target: app — after a source file is renamed and CMakeLists.txt still lists the old name. This guide reproduces both errors, shows the exact path CMake builds from a relative source name by resolving it against CMAKE_CURRENT_SOURCE_DIR, and explains why the second error is a knock-on of the first rather than a second bug. It then shows the other way to earn the No SOURCES error on its own: a source list that expands to nothing, through a file(GLOB) pattern that matches no files, with the empty expansion printed and fixed.
-
Fix "Undefined Reference to Vtable" — the Missing Virtual Function
A class with virtual functions compiles in every file and then fails to link with a single undefined reference to the vtable for the class, naming no function at all. This guide reproduces that error, explains why the vtable is emitted alongside one particular member function — the first non-inline virtual, called the key function — and shows how to find which declared virtual was never defined. It covers the three fixes (define the function, make it pure virtual, define it inline), the nm check that proves where the vtable went missing, and the destructor variant whose error names the destructor and the typeinfo instead.
-
Fix Template "Undefined Reference" — Why Template Definitions Cannot Hide in a .cpp
A class template declared in a header and defined in a .cpp file compiles in both files and then fails to link with undefined references to every member the program uses. This guide reads the linker output, explains why the using file cannot generate the code and the defining file never does, and fixes it two ways: the definitions move into the header, or explicit instantiation in the .cpp turns the template into a closed set of types. It also shows the trap that follows the second fix — the first new type brings the same error back — and the member that never needed a definition at all.
-
Fix "Multiple Definition" Link Errors — Header Definitions and inline
A function and a variable defined in a header included by two source files fail to link with multiple definition errors for both. This guide reads the linker output line by line, traces it to the One Definition Rule, and fixes the header two ways: inline on the function and the variable, and a declaration in the header with the single definition in one source file. It also shows the static trap, where the link succeeds and each file silently gets its own counter.
-
Fix "Cannot Find -l..." — How ld Searches for Libraries, and Where the Path Is Set
The link fails with a single line — cannot find -lgreet — even though the library file is sitting in the project. This guide reproduces that error with a small library built in a lib directory, shows the exact filename the linker constructs from a -l option and the directories it searches for that name, and separates the three causes the one line hides: the file is not there, the name does not match, or the directory is not on the search path. It covers the -L fix, the full-path fix, the CMake find_library form, and the shared-library variant where the same command starts linking and the failure moves to program start instead.
-
C++ Variables and Data Types: Declaration, Initialization, and Sizes
Declare a C++ variable, initialize it three ways, and read what sizeof reports: int 4 bytes, double 8, bool 1. Includes the brace-init narrowing error, the uninitialized-variable warning, integer division, and bool printing.
-
C++ STL Containers: vector, map, and set by Example
Use the three containers beginners reach for first: vector for an ordered list that grows, map for lookup by name, set for unique values in sorted order.
-
C++ Pointers and References: Addresses, Dereferencing, and nullptr
Learn C++ pointers and references by running code: address-of and dereference, why a pointer can be re-pointed and a reference cannot, pass-by-reference, pointer arithmetic on an array, and nullptr. Every number below is the output of a program run.
-
C++ Loops: for, while, do-while, and Range-for
The four C++ loop forms: a counted for loop sums 1 to 5 and prints for sum=15, a while loop counts down from 3, a range-for walks a vector of 10, 20, 30 with no index, and a do-while runs once even when its condition starts false. The same programs show break and continue, the off-by-one difference between < and <=, and why a range-for needs a reference to change the values it visits.
-
C++ Functions: Parameters, Overloads, and Default Arguments
C++ functions: two add overloads print add int=5 and add double=6, a default argument makes mult(5) print 10 while mult(5, 3) prints 15, and a swap through references prints swapped x=2 y=1. The same code shows why pass-by-value leaves the caller unchanged, why add(2, 3.5) fails to compile as ambiguous, and why a default argument must come last.
-
C++ Exceptions: try, catch, and throw, With the Program Still Running After
C++ exceptions: a divide function throws std::runtime_error on a zero divisor and the catch block prints caught: divide by zero, a thrown int is caught as int=42, and the program prints after catch, program continues. The same guide shows a std::vector .at() call throwing std::out_of_range, catch by value slicing a derived exception down to its base, and catch (...) receiving a throw it cannot name.
-
C++ Classes and Objects: Your First Class, Constructor, and Methods
Build your first C++ class by running code: a Counter class with a constructor initializer list, methods, const methods, and private members. The program prints hits=3, and every compiler error in the guide is quoted verbatim from a box run.
-
C++ Arrays and std::array: C Arrays, Bounds, and the Safe Replacement
C++ arrays: a C array of three ints prints size=3 from the sizeof idiom, a function that receives the array prints inside sizeof=8 because the array decayed to a pointer, and std::array prints b.size=3 and b sum=15. The same code shows std::array::at(5) throwing std::out_of_range, caught and printed, while operator[] does no bounds checking at all.