C++ Primer, Fifth Edition
A comprehensive and authoritative guide to C++, completely rewritten for the C++11 standard. This course covers everything from basic language elements to complex library facilities and advanced class-authoring tools.
Lessons
Lesson
This lesson introduces the fundamentals of C++ programming, focusing on the structure of the main function as the mandatory entry point for all applications. Students will learn how to configure their development environment, utilize standard input/output streams, and understand the importance of return values for program execution.
This lesson explores C++ stream-based logic, focusing on how to use input streams as boolean conditions to process data of indeterminate length. Students will learn to implement state-tracking algorithms and understand how user-defined classes can be integrated into stream operations for efficient data handling.
This lesson explores C++ primitive arithmetic types, including integral, floating-point, and void types, while explaining how they map to hardware memory. Students will learn to distinguish between signed and unsigned integers, understand memory representation, and select appropriate data types for specific programming tasks.
This lesson explores the fundamental differences between pointers and references in C++, focusing on how pointers store memory addresses while references act as permanent aliases for existing objects. Students will learn to implement complex data structures, apply const correctness, and utilize type qualifiers like volatile and restrict to ensure memory safety and performance.
This lesson explores efficient C++ namespace management by using declarations to streamline code and avoid repetitive prefixes. It also covers the importance of header guards in separate compilation to prevent redefinition errors and maintain clean, modular project structures.
This lesson explores the use of iterators as a universal mechanism for navigating diverse C++ containers, emphasizing the importance of the begin and end sentinel pattern for generic programming. Students will learn to perform standard iterator operations, understand the risks of iterator invalidation, and recognize why using inequality operators ensures code portability across different data structures.
This lesson explores the fundamental distinction between lvalues, which represent objects with persistent memory identities, and rvalues, which are transient values or literals. Students will learn how to identify these expressions, understand the rules for lvalue-to-rvalue conversions, and apply these concepts to operator precedence and memory management.
This lesson explores the fundamental structure of C++ statements, focusing on the use of expression statements, null statements, and compound blocks. Students will learn how to properly manage scope and avoid common logic errors, such as extraneous semicolons, while applying these concepts to control flow and algorithmic tasks.
This lesson explores the principles of function design, focusing on the distinction between lexical scope and execution lifetime for automatic objects. Students will learn to manage memory efficiently by understanding how parameters, local variables, and static variables behave within a program's stack.
This lesson explores the distinction between automatic and static object lifetimes in C++, explaining how they differ in memory allocation and persistence. You will learn how to manage local state effectively by choosing between stack-based automatic variables and function-scoped static objects.
This lesson explores the transition from structs to Abstract Data Types (ADTs) by implementing class encapsulation, access modifiers, and interface/implementation separation. Students will learn to design robust classes using constructors, nonmember interface functions, and friendship to protect internal state while maintaining functional flexibility.
This lesson explores the transition from passive data structures to Abstract Data Types (ADTs) in C++, emphasizing the role of encapsulation in maintaining internal state. Students will learn how to use classes to separate interfaces from implementation details while managing data integrity through access control and static members.
This lesson explores the C++ stream hierarchy, emphasizing that IO objects must be passed by non-const reference due to their non-copyable nature. It also covers the selection of sequential containers, highlighting the performance trade-offs between structures like vectors and lists based on access patterns and insertion requirements.
This lesson explores the relationship between C++ container size and capacity, emphasizing how memory reallocation affects iterator validity and performance. Students will learn to distinguish between container-specific operations and generic algorithms, while mastering the use of iterators to safely manipulate container contents.
This lesson explores the use of associative containers like std::map and std::set to achieve efficient logarithmic-time lookups, while contrasting ordered and unordered variants. It also covers implementing automated memory management using smart pointers (std::unique_ptr, std::shared_ptr, and std::weak_ptr) to handle shared resources safely.
This lesson explores the mechanics of C++ copy control, focusing on the distinction between initialization and assignment, the risks of synthesized copy operations, and the implementation of custom copy constructors and assignment operators. Students will learn to apply the Rule of Five to ensure robust resource management and prevent common memory errors like shallow copies and double-frees.
This lesson explores the philosophy of operator overloading in C++, focusing on how to implement unary and binary operators to make user-defined types behave like first-class citizens. Students will also learn to construct class hierarchies using inheritance, access control, and virtual functions to enable polymorphic behavior.
This lesson introduces generic programming in C++ by using templates as blueprints to create type-independent functions and classes. You will learn how the compiler performs instantiation to generate concrete code, the importance of minimizing type requirements for reusability, and why template definitions are typically placed in header files.
This lesson explores the use of `std::tuple` as a heterogeneous container for grouping multiple data types in large-scale C++ systems. Students will learn how to initialize, access, and compare tuples while evaluating when to use them versus custom structs for improved code efficiency and readability.
Course Overview
📚 Content Summary
A comprehensive and authoritative guide to C++, completely rewritten for the C++11 standard. This course covers everything from basic language elements to complex library facilities and advanced class-authoring tools.
The definitive industry standard guide for mastering modern C++11 programming.
Author: Stanley B. Lippman, Josée Lajoie, Barbara E. Moo
Acknowledgments: Dave Abrahams, Andy Koenig, Stephan T. Lavavej, Jason Merrill, John Spicer, Herb Sutter, Bjarne Stroustrup, Alex Stepanov, and members of the standardization committee.
🎯 Learning Objectives
- Define and implement the
mainfunction and understand its interaction with the operating system. - Execute command-line compilation and manage basic I/O streams (
cin,cout). - Apply flow-of-control statements to solve iterative logic problems, such as counting occurrences.
- Implement logical structures to count and process consecutive occurrences of input data.
- Differentiate between assignment (
=) and equality (==) operators within control statements. - Use class objects (
Sales_item), access member functions via the dot operator, and include custom header files. - Distinguish between different primitive types and predict the outcomes of type conversions and unsigned arithmetic wrap-around.
- Implement C++11 features including list initialization,
nullptr,constexpr, and type deduction specifiers. - Differentiate between variable declarations and definitions, and apply scope rules to manage identifier visibility.
- Distinguish between references and pointers, and utilize
void*for generic memory handling.
Lessons
Overview: This lesson introduces the foundational structure of a C++ program, focusing on the main function, basic data types, and the compilation process. It covers essential Input/Output (I/O) operations using the iostream library, logic implementation through while and for loops, and concludes with an introduction to object-oriented concepts via the Sales_item class.
Learning Outcomes:
- Define and implement the
mainfunction and understand its interaction with the operating system. - Execute command-line compilation and manage basic I/O streams (
cin,cout). - Apply flow-of-control statements to solve iterative logic problems, such as counting occurrences.
Overview: This lesson transitions from basic control flow to the fundamental power of C++: Classes. Learners will master the logic required to process streams of data (counting consecutive occurrences) and learn how to use the Sales_item class to handle complex data structures as easily as built-in types. The unit concludes with the implementation of a functional Bookstore Program, integrating file redirection and error reporting.
Learning Outcomes:
- Implement logical structures to count and process consecutive occurrences of input data.
- Differentiate between assignment (
=) and equality (==) operators within control statements. - Use class objects (
Sales_item), access member functions via the dot operator, and include custom header files.
Overview: This lesson establishes the foundational building blocks of C++ programming by exploring arithmetic types, variable lifecycles, and the memory model. Students will master the nuances of type conversions (particularly unsigned types), the C++11 list initialization syntax, and the critical distinctions between pointers and references. The lesson concludes with advanced type systems including const qualifiers, type deduction (auto, decltype), and the implementation of robust custom data structures using preprocessor guards.
Learning Outcomes:
- Distinguish between different primitive types and predict the outcomes of type conversions and unsigned arithmetic wrap-around.
- Implement C++11 features including list initialization,
nullptr,constexpr, and type deduction specifiers. - Differentiate between variable declarations and definitions, and apply scope rules to manage identifier visibility.
Overview: This lesson explores the sophisticated type system of C++11, focusing on how compound types (pointers and references) interact with type qualifiers like const and constexpr. Students will master the nuances of type deduction using auto and decltype, and learn to encapsulate data within custom structures protected by preprocessor header guards.
Learning Outcomes:
- Distinguish between references and pointers, and utilize
void*for generic memory handling. - Categorize and apply top-level and low-level
constqualifications andconstexprfor compile-time constants. - Implement C++11 type deduction (
autoanddecltype) to write flexible, maintainable code.
Overview: This lesson covers the fundamental C++ Standard Library types string and vector, which provide more flexible and safer alternatives to built-in types. Students will learn how to manage namespace access via using declarations, initialize and manipulate variable-length strings and containers, and use range-based for loops and iterators to process data collections efficiently.
Learning Outcomes:
- Simplify code using
namespace usingdeclarations while avoiding common pitfalls in header files. - Perform robust string and vector initialization, including C++11 list initialization.
- Implement character-level processing and dynamic container growth using
push_back, range-basedforloops, and basic iterator operations.
Overview: This lesson covers the fundamental mechanisms for navigating and managing sequences in C++11. It moves from modern high-level tools like iterators for string and vector to low-level built-in arrays, pointer arithmetic, and C-style character strings. Students will learn how to interface legacy array-based code with modern standard library containers and manage complex multidimensional structures.
Learning Outcomes:
- Use iterators and iterator arithmetic to navigate and manipulate
stringandvectorcontainers. - Define, initialize, and navigate built-in arrays using pointer arithmetic and the
begin/endlibrary functions. - Implement C-style string operations and safely interface built-in arrays with modern library types.
Overview: This lesson covers the fundamental building blocks of C++ expressions, focusing on how the language evaluates operations and manages data types. Students will master the distinction between lvalues and rvalues, the rules of operator precedence and associativity, and the mechanics of arithmetic, logical, and bitwise operations. Additionally, the lesson provides a deep dive into C++ type management, including implicit arithmetic conversions and the safe application of explicit named casts.
Learning Outcomes:
- Distinguish between lvalues (object identity) and rvalues (object value) and understand their role in expressions.
- Predict the evaluation order of complex expressions using precedence, associativity, and short-circuit logic.
- Perform low-level data manipulation using bitwise operators and manage type safety through implicit conversions and explicit named casts.
Overview: This lesson covers the essential C++ control flow structures, ranging from basic statement types and scoping rules to advanced conditional and iterative logic. It also introduces robust error-handling techniques using C++ exception handling mechanisms and the standard library exception hierarchy.
Learning Outcomes:
- Distinguish between null, simple, and compound statements and manage variable scope within these structures.
- Implement complex decision-making using
ifandswitchstatements while resolving logic errors like the "dangling else." - Select and apply the appropriate iterative construct (
while,for, rangefor,do while) for specific programming tasks.
Overview: This lesson covers the architecture of C++ functions, focusing on how data is passed into and returned from modular code blocks. It explores the lifecycle of local objects, the mechanics of argument passing (value vs. reference), and the C++11 standard for handling varying parameters. Mastery of these concepts allows programmers to write efficient, reusable, and memory-safe code.
Learning Outcomes:
- Distinguish between parameter initialization methods and their impact on performance and data integrity.
- Implement robust function interfaces using
constqualifiers,initializer_list, and array-passing techniques. - Manage object lifetimes effectively using automatic and static storage durations.
Overview: This lesson covers the intricate mechanics of C++ functions, focusing on parameter passing, object lifetimes, and the complexities of function overloading. Students will master C++11 features such as initializer_list for varying parameters, constexpr functions, and the declaration and use of function pointers to create flexible, modular code.
Learning Outcomes:
- Differentiate between pass-by-value and pass-by-reference and identify when to use
constparameters. - Apply the rules of overload resolution to determine the "best match" among candidate and viable functions.
- Implement and manage function pointers, including their use in containers like vectors and as return types.
Overview: This lesson covers the transition from simple data structures to Abstract Data Types (ADTs) in C++. It focuses on the mechanics of class design, including member functions, the implicit this pointer, and the critical role of constructors in object initialization. Furthermore, it explores encapsulation through access control (public/private) and the use of "friends" to maintain a clean interface while hiding implementation details.
Learning Outcomes:
- Design and implement a C++ class (like
Sales_data) that separates its interface from its implementation. - Master the rules of object initialization using default, overloaded, and explicit constructors.
- Apply access specifiers and friendship to enforce encapsulation and manage class scope.
Overview: This lesson covers the advanced mechanics of C++ class design, focusing on the transition from simple data structures to robust Abstract Data Types (ADTs). Key topics include managing object initialization through various constructor types, controlling implicit type conversions using the explicit keyword, and understanding class-level entities like static members and literal classes.
Learning Outcomes:
- Design and implement encapsulated classes (ADTs) using access specifiers and friend declarations.
- Manage implicit class-type conversions and suppress them using the
explicitkeyword. - Implement and initialize
staticclass members for class-wide data management.
Overview: This lesson covers the fundamental mechanics of the C++ standard library's IO system and sequential containers. Students will learn to manage stream condition states and output buffers, perform file and string-based I/O, and navigate the library's sequential containers. The lesson emphasizes the critical concepts of iterator ranges, container initialization, and the performance implications of container memory management.
Learning Outcomes:
- Interrogate and reset stream condition states and control output buffer flushing to manage stream integrity.
- Utilize
fstreamandsstreamfor persistent and in-memory data handling using various file modes. - Choose appropriate sequential containers based on access patterns and memory overhead to optimize selection.
Overview: This lesson covers the management of C++ sequential containers and the application of generic algorithms to process data independently of container types. It explores how containers handle memory growth and element lifecycle, alongside the use of lambdas and function binders to customize library algorithms. Students will master the library's architecture, including iterator categories and specialized algorithms.
Learning Outcomes:
- Manage container life-cycles using specialized operations for
forward_list, resizing techniques, andvectorcapacity management. - Perform complex string manipulations and numeric conversions using the extended
stringlibrary and container adaptors. - Implement generic algorithms to read, write, and reorder data while customizing behavior through predicates, lambda expressions, and
std::bind.
Overview: This lesson covers the C++11 standard for associative containers and dynamic memory management. It details the use of ordered and unordered containers for efficient key-based retrieval and the implementation of robust, exception-safe code using smart pointers. The lesson concludes with the design of a real-world Text-Query application that integrates these complex data structures.
Learning Outcomes:
- Implement and manipulate associative containers using efficient lookup, insertion, and subscripting techniques.
- Master dynamic memory management by transitioning from manual
new/deleteto RAII-based smart pointers and theallocatorclass. - Design complex systems that share data safely across classes using reference counting and smart pointer ownership.
Overview: This lesson explores how C++ classes control the lifecycle of their resources through the "Big Five" special member functions. Students will learn to manage dynamic memory using value-like and pointer-like strategies, implement the exception-safe copy-and-swap idiom, and optimize performance using C++11 move semantics and rvalue references.
Learning Outcomes:
- Implement and explain the Rule of Three/Five to ensure proper resource management and prevent memory leaks.
- Distinguish between value-like and pointer-like class behaviors and implement reference counting.
- Apply move semantics using rvalue references and
std::moveto eliminate unnecessary deep copies of large objects.
Overview: This lesson explores extending the language's syntax through operator overloading and building extensible systems via Object-Oriented Programming (OOP). Students will learn to design classes that integrate with built-in operations while mastering the mechanics of inheritance, dynamic binding, and polymorphic class hierarchies.
Learning Outcomes:
- Design and implement overloaded operators that follow C++ standard library conventions.
- Create and utilize function objects and the
functiontype wrapper to unify callable entities. - Construct robust inheritance hierarchies using virtual functions, abstract base classes, and C++11 access specifiers.
Overview: This lesson covers the fundamental and advanced mechanics of C++ templates, providing the foundation for generic programming. Students will move from defining basic function and class templates to mastering C++11 specific features such as variadic templates, perfect forwarding, and template specialization.
Learning Outcomes:
- Define and instantiate function and class templates using both type and nontype parameters.
- Manage the template compilation model and control instantiation across multiple files using
extern template. - Implement advanced deduction techniques, including trailing return types and perfect forwarding with
std::forward.
Overview: This lesson covers advanced C++11 standard library components and language features designed for complex system development. It spans specialized data structures, robust pattern matching via the regex library, and architectural tools for large-scale programming. Furthermore, it explores advanced exception handling, namespace management, and the complexities of multiple inheritance.
Learning Outcomes:
- Utilize
tuplefor multiple return values andbitsetfor efficient bit-level flag management. - Implement complex string pattern matching, validation, and transformation using the
regexlibrary. - Generate high-quality random numbers using engines and distributions while maintaining proper state and seeding.