The C++ Workshop - Learn to write clean, maintainable code in C++ and advance your career in software engineering. [1 ed.] 9781839216626

C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than

3,244 90 7MB

English Pages 605 Year 2021

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover
FM
Copyright
Table of Contents
Preface
Chapter 1: Your First C++ Application
Introduction
Advantages of C++
Anatomy of a C++ Application
Exercise 1: Compiling Our First Application
C++ Build Pipeline
C++ Keywords
Keyword Examples
Preprocessor Directives
Include
Macros
Conditional Compilation
Exercise 2: Defining Values with Preprocessor Directives
Basic I/O Statements
Exercise 3: Reading User Details
Functions
Passing by Value, Passing by Reference
Why Are We Outputting 10?
Function Overloading
Default Parameters
Exercise 4: Functions
Activity 1: Writing Your Own C++ Application
Summary
Chapter 2: Control Flow
Introduction
if/else
Exercise 5: Implementing if/else Statements
Ternary Operator
Exercise 6: Creating a Simple Menu Program Using an if/else Statement
switch/case
Exercise 7: Refactor an if/else Chain into switch/case
Loops
while
Exercise 8: Implementing a while Loop
do while
Exercise 9: Implementing while and do while Loops with a False Condition
for
Exercise 10: Implementing a for Loop
Range-based for loop
Exercise 11: Generating Random Numbers Using Loops
break/continue
break
continue
Exercise 12: Making a Loop More Efficient Using break and continue
Activity 2: Creating a Number-Guessing Game Using Loops and Conditional Statements
Summary
Chapter 3: Built-In Data Types
Introduction
Data Types
Type Modifiers
Built-In Types
Reference Table
Exercise 13: Declaring Data Types
Containers
Arrays
Initialization
Accessing Elements
Array Memory
Exercise 14: Implementing Containers to Store Usernames
Multidimensional Arrays
Exercise 15: Using Multidimensional Arrays to Store More Data
Vectors
Accessing Elements
Exercise 16: Looping over a Vector
Initialization
Modifying Elements
Exercise 17: Modifying a Vector
Classes/Structs
Classes
Structs
Access Modifiers
Exercise 18: Using Accessibility Modifiers to Control Access
Constructors/Destructors
Exercise 19: Classes/Struct
Storage Lifetime
Exercise 20: Storage Lifetime Example
Static
Activity 3: Sign-Up Application
Summary
Chapter 4: Operators
Introduction
Arithmetic Operators
Exercise 21: The Prime Number Checker
Relational Operators
Equality
Comparison
Exercise 22: The Time-of-Day Calculator
Unary Operators
Exercise 23: A Pre-Increment/Post-Increment Example
Assignment Operators
Logical Operators
Exercise 24: Logical Operators Example
Operator Overloading
Exercise 25: Operator Overloading Example
Bitwise Operators
Activity 4: Fizz Buzz
Summary
Chapter 5: Pointers and References
Introduction
Memory Addresses
Pointers
Exercise 26: Pointers
Exercise 27: Dereferencing nullptr
Pointers to Arrays
Exercise 28: Pointers to Arrays
Pointer Arithmetic
Exercise 29: Pointer Arithmetic
Exercise 30: Incrementing Pointers
Pointers to Pointers
Exercise 31: Pointers to Pointers
References
Exercise 32: References
Exercise 33: Bad References
Pointers and References as Function Arguments
Exercise 34: Pointers as Function Arguments
Pointers to Classes or Structs
Exercise 35: Pointers to Class Instance
References as Function Arguments
Exercise 36: References as Function Arguments
Activity 5: Using Pointers and References to Manipulate an Array of Strings
Summary
Chapter 6: Dynamic Variables
Introduction
Dynamic Variables
Exercise 37: Creating and Deleting Dynamic Variables of Basic Types
Exercise 38: Creating and Deleting Dynamic Class Instances
Dynamic Arrays
Exercise 39: Creating and Deleting Dynamic Arrays of Basic Types
Exercise 40: Creating and Deleting Dynamic Arrays of Classes
Seven Dynamic Variable Sins
Exercise 41: Using a Dynamic Variable before Creating It
Exercise 42: Using a Dynamic Variable after Deleting It
Exercise 43: Not Deleting a Dynamic Variable
Exercise 44: Overwriting a Pointer to a Dynamic Variable
Exercise 45: Deleting a Dynamic Variable Twice
Exercise 46: Deleting a Dynamic Array with delete instead of delete[]
Exercise 47: Deleting a Dynamic Variable with delete[] instead of delete
Dynamic Containers
Linked Lists
Binary Search Trees
Recursive Data Structures
Visiting Items in a Recursive Data Structure
Finding Items
Adding Items
Deleting Dynamic Items
Exercise 48: Creating Linked Lists of Class Instances
Activity 6: Creating Binary Search Trees of Class Instances
Summary
Chapter 7: Ownership and Lifetime of Dynamic Variables
Introduction
The Lifetime of Dynamic Variables
Ownership of Dynamic Variables
Resource Acquisition Is Initialization (RAII)
Exercise 49: Lifetime Demonstration
Exercise 50: Owned Pointers in Data Structures
Exercise 51: Transfer of Ownership
Smart Pointers — Automated Ownership of Dynamic Variables
unique_ptr
Exercise 52: Working with unique_ptr
make_unique()
Exercise 53: Using make_unique()
unique_ptr as a Class Member Variable
Exercise 54: Using unique_ptr as a Class Member Variable
unique_ptr in Function Arguments and Return Values
Exercise 55: Using unique_ptr in Function Return Values
Shared Ownership of Dynamic Variables
Exercise 56: Using shared_ptr
make_shared()
Exercise 57: Using make_shared()
Activity 7: Storing the Words of a Book Using Dynamic Variables
Summary
Chapter 8: Classes and Structs
Introduction
Classes versus Structs
Unions
Constructors and Destructors
Constructors
Default Constructors
Exercise 58: Defining a Default Constructor
Parameterized Constructors
Exercise 59: Defining a Parameterized Constructor
Copy Constructors
Shallow Copy or Deep Copy
Exercise 60: Defining a Copy Constructor
Copy Assignment Operator
Exercise 61: Overloading the Assignment Operator
Destructors
Activity 8: Creating a VideoClip Class
Summary
Chapter 9: Object-Oriented Principles
Introduction
Classes and OOP
S in SOLID
Exercise 62: Creating a Class that Prints Values
Encapsulation
Exercise 63: Creating a Position Class with Private Member Variables
Getters and Setters
Exercise 64: Getters and Setters in a Position Class
Return Value or Reference
Return by Value
Return by Reference
const
Returning const References
Const Functions
Abstraction
Activity 9: A Basic RPG Combat System
Summary
Chapter 10: Advanced Object-Oriented Principles
Introduction
Inheritance
Exercise 65: Inheritance
Multiple Inheritance
Exercise 66: Multiple Inheritance
Access Modifiers and Inheritance
Exercise 67: Access Modifiers and Inheritance
Virtual Functions
Pure Virtual Functions/Abstract Classes
Exercise 68: Virtual Functions
Polymorphism
Exercise 69: Polymorphism
Casting between Types
Static Cast
Dynamic Cast
C-Style Cast
Exercise 70: Casting
Activity 10: An Encyclopedia Application
Summary
Chapter 11: Templates
Introduction
Syntax
Template Classes
Exercise 71: Creating Different Types for the Position Objects
Multiple Template Parameters
Template Functions
Exercise 72: Comparing Position Values Using a Template Function
Template Specialization
Additional Template Considerations
Forcing Accepted Types
Templates and Default Constructors
Creating a Generic Queue
What Is a Queue?
Implementing Constructors and Destructors in the Queue
Dynamic Memory
Allocators
Resizing and Appending
Pushing and Popping
Finalizing and Testing
Activity 11: Creating a Generic Stack
Summary
Chapter 12: Containers and Iterators
Introduction
Containers
A String Is a Container
String Constructors
Exercise 73: Creating Strings
Assigning to Strings
Operations on Strings
Iterators
Further Research
Exercise 74: Is It a Palindrome?
Vectors-Handy, Resizable Arrays
Vector Constructors
Vector Assignment
Exercise 75: Accessing Elements in a Vector
Operations on Vectors
Searching Vectors
Exercise 76: Sorting Vectors with a Custom Comparison
Map/Unordered Map: Our Associative Containers
Constructing Maps and Unordered Maps
Operations on Maps and Unordered Maps
Exercise 77: Map Quiz
Sets/Multisets
Constructors
Exercise 78: A Custom Comparator for a Set
Operations
Exercise 79: Using a Set to Get the Number of Unique Elements in a Multiset
Queues/Stacks
Constructors
Operations
Activity 12: Converting RPG Combat to Use Standard Library Containers
Summary
Chapter 13: Exception Handling in C++
Introduction
Responding to Unexpected Events
Throwing Exceptions
Uncaught Exceptions
Exercise 80: Throwing Uncaught Exceptions
Catching Exceptions
Exercise 81: try/catch Blocks
Exercise 82: Exceptions Thrown by C++
Unwinding the Stack
RAII (Resource Acquisition Is Initialization) and Exception Handling
Exercise 83: Unwinding the Stack
Activity 13: Handling Exceptions
Summary
Appendix
Index
Recommend Papers

The C++ Workshop - Learn to write clean, maintainable code in C++ and advance your career in software engineering. [1 ed.]
 9781839216626

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

The C++ Workshop

Learn to write clean, maintainable code in C++ and advance your career in software engineering

Dale Green Kurt Guntheroth Shaun Ross Mitchell

The C++ Workshop Copyright © 2020 Packt Publishing All rights reserved. No part of this course may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this course. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Authors: Dale Green, Kurt Guntheroth, and Shaun Ross Mitchell Reviewers: Anil Achary, Brent Arnold, Andrew Dent, Paras Gaba, and Archit Goyal Managing Editor: Mahesh Dhyani Acquisitions Editor: Alicia Wooding Production Editor: Samita Warang Editorial Board: Shubhopriya Banerjee, Bharat Botle, Ewan Buckingham, Megan Carlisle, Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Bridget Neale, Dominic Pereira, Shiny Poojary, Abhishek Rane, Brendan Rodrigues, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray First published: February 2020 Production reference: 2241220 ISBN 978-1-83921-662-6 Published by Packt Publishing Ltd. Livery Place, 35 Livery Street Birmingham B3 2PB, UK

Table of Contents Preface   i Chapter 1: Your First C++ Application   1 Introduction .....................................................................................................  2 Advantages of C++ ................................................................................................ 3

Anatomy of a C++ Application .......................................................................  3 Exercise 1: Compiling Our First Application ...................................................... 5 C++ Build Pipeline ................................................................................................. 8

C++ Keywords ................................................................................................  10 Keyword Examples ............................................................................................. 12

Preprocessor Directives ...............................................................................  13 Include  ................................................................................................................. 13 Macros .................................................................................................................. 14 Conditional Compilation .................................................................................... 17 Exercise 2: Defining Values with Preprocessor Directives ............................. 21

Basic I/O Statements ....................................................................................  23 Exercise 3: Reading User Details ....................................................................... 27

Functions .......................................................................................................  29 Passing by Value, Passing by Reference ........................................................... 31 Why Are We Outputting 10? ........................................................................ 32 Function Overloading ......................................................................................... 33 Default Parameters ............................................................................................ 35 Exercise 4: Functions .......................................................................................... 36 Activity 1: Writing Your Own C++ Application ................................................. 39

Summary ........................................................................................................  40

Chapter 2: Control Flow   43 Introduction ...................................................................................................  44 if/else ..............................................................................................................  44 Exercise 5: Implementing if/else Statements .................................................. 46 Ternary Operator ................................................................................................ 49 Exercise 6: Creating a Simple Menu Program Using an if/else Statement ........................................................................................... 50

switch/case ....................................................................................................  53 Exercise 7: Refactor an if/else Chain into switch/case ................................... 55

Loops ..............................................................................................................  57 while ..................................................................................................................... 58 Exercise 8: Implementing a while Loop ............................................................ 59 do while ................................................................................................................ 62 Exercise 9: Implementing while and do while Loops with a False Condition ........................................................................................ 64 for ......................................................................................................................... 65 Exercise 10: Implementing a for Loop .............................................................. 67 Range-based for loop ......................................................................................... 69 Exercise 11: Generating Random Numbers Using Loops .............................. 70

break/continue ..............................................................................................  74 break .................................................................................................................... 74 continue ............................................................................................................... 78 Exercise 12: Making a Loop More Efficient Using break and continue ........ 79 Activity 2: Creating a Number-Guessing Game Using Loops and Conditional Statements .................................................................. 82

Summary ........................................................................................................  84

Chapter 3: Built-In Data Types   87 Introduction ...................................................................................................  88 Data Types .....................................................................................................  89 Type Modifiers ..................................................................................................... 89 Built-In Types ....................................................................................................... 90 Reference Table .................................................................................................. 90 Exercise 13: Declaring Data Types .................................................................... 91

Containers .....................................................................................................  93 Arrays ................................................................................................................... 93 Initialization ......................................................................................................... 95 Accessing Elements ............................................................................................ 98 Array Memory ..................................................................................................... 99 Exercise 14: Implementing Containers to Store Usernames ......................  100 Multidimensional Arrays .................................................................................  103 Exercise 15: Using Multidimensional Arrays to Store More Data ..............  104 Vectors ..............................................................................................................  107 Accessing Elements .........................................................................................  108 Exercise 16: Looping over a Vector ................................................................  109 Initialization ......................................................................................................  111 Modifying Elements .........................................................................................  111 Exercise 17: Modifying a Vector .....................................................................  112

Classes/Structs ............................................................................................  114 Classes ...............................................................................................................  115 Structs ...............................................................................................................  116 Access Modifiers ..............................................................................................  118 Exercise 18: Using Accessibility Modifiers to Control Access .....................  119 Constructors/Destructors ...............................................................................  121 Exercise 19: Classes/Struct .............................................................................  124

Storage Lifetime ..........................................................................................  127 Exercise 20: Storage Lifetime Example .........................................................  128 Static ..................................................................................................................  130 Activity 3: Sign-Up Application .......................................................................  132

Summary ......................................................................................................  135

Chapter 4: Operators   137 Introduction .................................................................................................  138 Arithmetic Operators .................................................................................  138 Exercise 21: The Prime Number Checker ......................................................  142

Relational Operators ..................................................................................  145 Equality .............................................................................................................  145 Comparison ......................................................................................................  147 Exercise 22: The Time-of-Day Calculator .......................................................  149

Unary Operators .........................................................................................  152 Exercise 23: A Pre-Increment/Post-Increment Example .............................  155

Assignment Operators ...............................................................................  156 Logical Operators ........................................................................................  158 Exercise 24: Logical Operators Example .......................................................  158

Operator Overloading ................................................................................  161 Exercise 25: Operator Overloading Example ................................................  163

Bitwise Operators .......................................................................................  165 Activity 4: Fizz Buzz ..........................................................................................  169

Summary ......................................................................................................  170

Chapter 5: Pointers and References   173 Introduction .................................................................................................  174 Memory Addresses .....................................................................................  175 Pointers .............................................................................................................  175

Exercise 26: Pointers ........................................................................................  177 Exercise 27: Dereferencing nullptr ................................................................  179 Pointers to Arrays ............................................................................................  180 Exercise 28: Pointers to Arrays .......................................................................  181 Pointer Arithmetic ...........................................................................................  182 Exercise 29: Pointer Arithmetic ......................................................................  183 Exercise 30: Incrementing Pointers ...............................................................  185 Pointers to Pointers .........................................................................................  189 Exercise 31: Pointers to Pointers ...................................................................  189

References ...................................................................................................  191 Exercise 32: References ...................................................................................  192 Exercise 33: Bad References ...........................................................................  194 Pointers and References as Function Arguments .......................................  196 Exercise 34: Pointers as Function Arguments ..............................................  196 Pointers to Classes or Structs .........................................................................  199 Exercise 35: Pointers to Class Instance .........................................................  200 References as Function Arguments ...............................................................  204 Exercise 36: References as Function Arguments .........................................  204 Activity 5: Using Pointers and References to Manipulate an Array of Strings ...........................................................................................  208

Summary ......................................................................................................  209

Chapter 6: Dynamic Variables   211 Introduction .................................................................................................  212 Dynamic Variables ......................................................................................  212 Exercise 37: Creating and Deleting Dynamic Variables of Basic Types .....  215 Exercise 38: Creating and Deleting Dynamic Class Instances ....................  219 Dynamic Arrays ................................................................................................  222 Exercise 39: Creating and Deleting Dynamic Arrays of Basic Types ..........  222

Exercise 40: Creating and Deleting Dynamic Arrays of Classes .................  225

Seven Dynamic Variable Sins ....................................................................  227 Exercise 41: Using a Dynamic Variable before Creating It ..........................  227 Exercise 42: Using a Dynamic Variable after Deleting It .............................  229 Exercise 43: Not Deleting a Dynamic Variable .............................................  231 Exercise 44: Overwriting a Pointer to a Dynamic Variable .........................  232 Exercise 45: Deleting a Dynamic Variable Twice ..........................................  235 Exercise 46: Deleting a Dynamic Array with delete instead of delete[] ....  237 Exercise 47: Deleting a Dynamic Variable with delete[] instead of delete ..............................................................................................  240

Dynamic Containers ...................................................................................  242 Linked Lists .......................................................................................................  243 Binary Search Trees .........................................................................................  243 Recursive Data Structures ..............................................................................  244 Visiting Items in a Recursive Data Structure ................................................  245 Finding Items ....................................................................................................  246 Adding Items ....................................................................................................  248 Deleting Dynamic Items ..................................................................................  249 Exercise 48: Creating Linked Lists of Class Instances ..................................  249 Activity 6: Creating Binary Search Trees of Class Instances .......................  256

Summary ......................................................................................................  258

Chapter 7: Ownership and Lifetime of Dynamic Variables   261 Introduction .................................................................................................  262 The Lifetime of Dynamic Variables ................................................................  262 Ownership of Dynamic Variables ...................................................................  263 Resource Acquisition Is Initialization (RAII) ..................................................  263 Exercise 49: Lifetime Demonstration ............................................................  264 Exercise 50: Owned Pointers in Data Structures .........................................  268

Exercise 51: Transfer of Ownership ...............................................................  273

Smart Pointers — Automated Ownership of Dynamic Variables .........  276 unique_ptr ....................................................................................................  276 Exercise 52: Working with unique_ptr .......................................................  277 make_unique() ..................................................................................................  282 Exercise 53: Using make_unique() .................................................................  282 unique_ptr as a Class Member Variable ...................................................  284 Exercise 54: Using unique_ptr as a Class Member Variable ...................  285 unique_ptr in Function Arguments and Return Values ..........................  289 Exercise 55: Using unique_ptr in Function Return Values ......................  289

Shared Ownership of Dynamic Variables ................................................  291 Exercise 56: Using shared_ptr  ...................................................................  292 make_shared() ..................................................................................................  296 Exercise 57: Using make_shared() ..................................................................  297 Activity 7: Storing the Words of a Book Using Dynamic Variables ............  299

Summary ......................................................................................................  301

Chapter 8: Classes and Structs   303 Introduction .................................................................................................  304 Classes versus Structs ................................................................................  304 Unions ..........................................................................................................  305 Constructors and Destructors ...................................................................  307 Constructors .....................................................................................................  307 Default Constructors .......................................................................................  307 Exercise 58: Defining a Default Constructor .................................................  309 Parameterized Constructors ..........................................................................  311 Exercise 59: Defining a Parameterized Constructor ....................................  312 Copy Constructors ...........................................................................................  314

Shallow Copy or Deep Copy ............................................................................  315 Exercise 60: Defining a Copy Constructor .....................................................  323 Copy Assignment Operator ............................................................................  325 Exercise 61: Overloading the Assignment Operator ...................................  328 Destructors .......................................................................................................  330 Activity 8: Creating a VideoClip Class ............................................................  330

Summary ......................................................................................................  332

Chapter 9: Object-Oriented Principles   335 Introduction .................................................................................................  336 Classes and OOP .........................................................................................  336 S in SOLID ..........................................................................................................  338 Exercise 62: Creating a Class that Prints Values ..........................................  339 Encapsulation ...................................................................................................  342 Exercise 63: Creating a Position Class with Private Member Variables ............................................................................................  345 Getters and Setters ..........................................................................................  348 Exercise 64: Getters and Setters in a Position Class ....................................  351

Return Value or Reference ........................................................................  354 Return by Value ................................................................................................  355 Return by Reference ........................................................................................  356 const ..................................................................................................................  359 Returning const References ...........................................................................  359 Const Functions ................................................................................................  361 Abstraction .......................................................................................................  362 Activity 9: A Basic RPG Combat System .........................................................  366

Summary ......................................................................................................  367

Chapter 10: Advanced Object-Oriented Principles   369 Introduction .................................................................................................  370 Inheritance ..................................................................................................  370 Exercise 65: Inheritance ..................................................................................  373

Multiple Inheritance ...................................................................................  375 Exercise 66: Multiple Inheritance  ..................................................................  379 Access Modifiers and Inheritance ..................................................................  381 Exercise 67: Access Modifiers and Inheritance ............................................  382 Virtual Functions ..............................................................................................  384 Pure Virtual Functions/Abstract Classes .......................................................  387 Exercise 68: Virtual Functions ........................................................................  389

Polymorphism .............................................................................................  391 Exercise 69: Polymorphism .............................................................................  393

Casting between Types ..............................................................................  396 Static Cast .........................................................................................................  397 Dynamic Cast ....................................................................................................  397 C-Style Cast .......................................................................................................  398 Exercise 70: Casting .........................................................................................  399 Activity 10: An Encyclopedia Application ......................................................  400

Summary ......................................................................................................  403

Chapter 11: Templates   405 Introduction .................................................................................................  406 Syntax  ..........................................................................................................  406 Template Classes .............................................................................................  407 Exercise 71: Creating Different Types for the Position Objects  ................  407 Multiple Template Parameters ......................................................................  410 Template Functions .........................................................................................  412

Exercise 72: Comparing Position Values Using a Template Function ........  413 Template Specialization ..................................................................................  415 Additional Template Considerations .............................................................  418 Forcing Accepted Types............................................................................... 418 Templates and Default Constructors........................................................ 419

Creating a Generic Queue ..........................................................................  421 What Is a Queue? .............................................................................................  422 Implementing Constructors and Destructors in the Queue ......................  424 Dynamic Memory .............................................................................................  426 Allocators...................................................................................................... 426 Resizing and Appending ..................................................................................  429 Pushing and Popping .......................................................................................  430 Finalizing and Testing ......................................................................................  431 Activity 11: Creating a Generic Stack .............................................................  433

Summary ......................................................................................................  434

Chapter 12: Containers and Iterators   437 Introduction .................................................................................................  438 Containers ...................................................................................................  438 A String Is a Container .....................................................................................  438 String Constructors ..........................................................................................  439 Exercise 73: Creating Strings ..........................................................................  439 Assigning to Strings .........................................................................................  442 Operations on Strings .....................................................................................  443 Iterators ............................................................................................................  445 Further Research .............................................................................................  447 Exercise 74: Is It a Palindrome? ......................................................................  447

Vectors-Handy, Resizable Arrays ..............................................................  451

Vector Constructors .........................................................................................  451 Vector Assignment ...........................................................................................  453 Exercise 75: Accessing Elements in a Vector ................................................  454 Operations on Vectors ....................................................................................  456 Searching Vectors ............................................................................................  456 Exercise 76: Sorting Vectors with a Custom Comparison ...........................  460

Map/Unordered Map: Our Associative Containers ................................  464 Constructing Maps and Unordered Maps .....................................................  464 Operations on Maps and Unordered Maps ..................................................  466 Exercise 77: Map Quiz ......................................................................................  468

Sets/Multisets ..............................................................................................  472 Constructors .....................................................................................................  472 Exercise 78: A Custom Comparator for a Set ................................................  473 Operations ........................................................................................................  476 Exercise 79: Using a Set to Get the Number of Unique Elements in a Multiset .....................................................................................  476

Queues/Stacks ............................................................................................  478 Constructors .....................................................................................................  479 Operations ........................................................................................................  479 Activity 12: Converting RPG Combat to Use Standard Library Containers ...........................................................................................  480

Summary ......................................................................................................  481

Chapter 13: Exception Handling in C++   483 Introduction .................................................................................................  484 Responding to Unexpected Events ...........................................................  485 Throwing Exceptions .......................................................................................  488 Uncaught Exceptions .......................................................................................  489 Exercise 80: Throwing Uncaught Exceptions ................................................  489

Catching Exceptions ........................................................................................  493 Exercise 81: try/catch Blocks ..........................................................................  494 Exercise 82: Exceptions Thrown by C++ ........................................................  497 Unwinding the Stack ........................................................................................  501 RAII (Resource Acquisition Is Initialization) and Exception Handling ........  502 Exercise 83: Unwinding the Stack ..................................................................  502 Activity 13: Handling Exceptions ....................................................................  508

Summary ......................................................................................................  510

Appendix   513 Index   579

>

Preface

About This section briefly introduces this course and software requirements in order to complete all of the included activities and exercises.

ii | Preface

About the Book C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library's built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.

About the Chapters Chapter 1, Your first C++ Application, will equip you with the fundamental tools and techniques required to get started building basic C++ applications. Chapter 2, Control Flow, presents various tools and techniques that are used to control the flow of execution throughout applications. Chapter 3, Built-in Data Types, presents the built-in data types provided by C++, including their fundamental properties and use within vectors and arrays. These are then utilized in the creation of a real-world sign-up application. Chapter 4, Operators, presents a variety of operators provided by C++, describing what they do and how they can allow us to manipulate our data. Chapter 5, Pointers and References, presents a variety of operators provided by C++, describing what they do and how they can allow us to manipulate our data. Chapter 6, Dynamic Variables, introduces dynamic variables – that is, variables that can be created when needed and can hold an arbitrarily large amount of data that is limited only by the memory that is available.

About the Book | iii Chapter 7, Ownership and Lifetime Of Dynamic Variables, makes the use of pointers in C++ programs safer and easier to understand. Chapter 8, Classes and Structs, presents the fundamentals of structs and classes with the aid of practical examples and exercises. Chapter 9, Object-Oriented Principles, presents best practices for designing classes and will give you an overview of abstraction and encapsulation, where to use them, and how they can benefit your custom C++ types. Chapter 10, Advanced Object-Oriented Principles, presents a number of advanced object-oriented principles, including inheritance and polymorphism, that will allow us to build more dynamic and powerful C++ applications. Chapter 11, Templates, covers an overview of templates and gives some examples of how they can be used and where and teaches you how to implement template types and functions. Chapter 12, Containers and Iterators, provides an overview of using the containers and iterators provided by the C++ standard library. Chapter 13, Exception Handling, covers exception handling, the mechanism used by C++ for reporting and recovering from unexpected events in a program.

Conventions Code words in text are shown as follows: "The #include line gives access to the name of the passed-in type through the name() function." A block of code is set as follows: #include #include using namespace std; template bool compare(T t1, T t2) {     return t1 == t2; }

New terms and important words are shown like this: "In the previous chapters, object-oriented programming (OOP) was introduced, along with examples and use cases."

iv | Preface Long code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. The permalinks to the entire code are placed below the code snippet. It should look as follows: Example09_1.cpp 23     string getName() 24     { 25         return m_trackName; 26     } 27  28     void setName(string newTrackName) 29     { 30         // if S-Club is not found set the track name - otherwise do nothing 31         if (newTrackName.find("S-Club") == string::npos) 32         { 33             m_trackName = newTrackName; 34          } 35     } 36  37     void setLength(float newTrackLength) 38     { 39         if (newTrackLength < MAX_TRACK_LENGTH && newTrackLength > 0) 40         // no prog metal for us! 41         { 42             m_lengthInSeconds = newTrackLength; 43         } 44     }

The complete code for this example can be found at: https://packt.live/2DLDVQf

Before You Begin There are many tools we can use to compile our C++ programs, too many to cover here, so here are some recommendations and a guide on getting started:

Online Compilers cpp.sh is an online C++ compiler and the one the authors extensively used in this book. Visit cpp.sh and ensure the options are set up as shown:

Figure 0.1: Screenshot of the cpp.sh online compiler

About the Book | v That is all we need to do to get started using this compiler. Simply write out your code and hit the run button. Any errors will appear in the compilation tab, and interactive standard input and output will be located on the execution tab. Here is a partial list of online C++ compilers you can use while working on the exercises. If the one you are using becomes sluggish, or you can't find it at all, try another: Tutorialspoint C++ compiler: This website allows you to compile a C++ program contained in a single file. It prints error messages from the operating system. You can find it at https://www.tutorialspoint.com/compile_cpp_online.php. godbolt compiler explorer: This website allows you to compile a single file on many different compilers and shows the output assembly language; its UI is a little subtle for some tastes. It prints error messages from the operating system. You can find it at https://godbolt.org/. coliru: This website allows you to compile a single file. It prints error messages from the operating system. You can find it at http://coliru.stacked-crooked.com/. repl.it: This website allows you to compile multiple files. You can find it at https://repl. it/languages/cpp. Rextester: This website lets you compile a single file using Microsoft Visual C++. You can find it at https://rextester.com/.

Installing the Code Bundle Download the code files from GitHub at https://github.com/PacktWorkshops/ The-CPP-Workshop and place them in a new folder called C:\Code. Refer to these code files for the complete code bundle. If you face any trouble with installation or with getting the code up and running, please reach out to the team at [email protected].

1

Your First C++ Application Overview This chapter equips you with the fundamental tools and techniques required to get started building basic C++ applications. We'll start by breaking a C++ application into its core components, identifying each by their role(s). We'll then take a look at the core language that defines C++, including pre-processor directives—statements that let us perform actions before our code is compiled. Finally, we'll look at how we get information in and out of our applications (I/O) before putting this all together in a final exercise in which you will write and run your own C++ application in an online compiler.

2 | Your First C++ Application

Introduction As the world becomes smarter, so do our devices. Everything from watches to our refrigerators now have the capacity to run code, a large portion of which is C++. Between 1972 and 1973 Dennis Richie authored the C programming language while working at Bell Labs. While great for efficiency, thanks to features such as low-level memory access, C is a procedural language and so does not provide object-orientated features. In response to this, Bjarne Stroustup, also while working at Bell Labs, began working on "C with classes" in 1979. In 1983, the language was renamed C++, and it saw its first commercial release two years later in 1985. Since then, it has gone through many standardizations, the last in December 2017, and continues to be governed by the International Organization for Standardization. Utilized in everything from operating systems to cutting-edge 3D game engines, C++ is the backbone of countless systems and industries, not least because of its high-performance capabilities, flexibility, and portability. C++ puts you close to the hardware, so it is often the tool of choice for performance-critical applications. The goal of this course is to demystify the C++ programming language, and to get you writing quality code as quickly as possible through a very pragmatic approach. While theory is certainly required, and will be covered where necessary, we'll mainly be focusing on practical application—learning by tackling real-world exercises and activities. To start our journey, we looked at a brief history of the language. While this alone won't make you a better programmer, it's always good to have context for what we're doing and why. By learning the origins of the language and how it's used in industry, we will set ourselves up with an informed starting point for the journey ahead. We're then going to jump right into dissecting a basic C++ application. By breaking an application down into its constituent parts, we can gain an understanding of the main pieces that it comprises. We'll then expand on this basic understanding by looking at each part in more detail throughout the rest of this introductory chapter. When we've concluded this chapter, we'll not only have an understanding of the origin of the language; we'll also be familiar with the different core parts of an application. We'll be able to look at an example C++ application with a sense of meaning and understanding. We'll then use this basic understanding to springboard into the next chapter, where we'll look deeper into the language at specific features and functionality.

Anatomy of a C++ Application | 3

Advantages of C++ Before we dive into the structure of a C++ program, let's have a look at a few key benefits of the language: • Performance: By putting the programmer close to the hardware, C++ allows us to write very efficient programs. Along with low-level memory access, the abstraction between code and what the machine will do is smaller than in most other languages, meaning you can manipulate the system better. • Portability: C++ can be cross-compiled to a wide array of platforms, and runs on everything from watches to televisions. If you're writing an application or library for more than one platform, C++ shines. • General purpose: C++ is a general-purpose programming language, and is used in everything from video games to enterprise. With a rich feature set spanning everything from direct memory management to classes and other Object-Oriented Programming (OOP) principles, you can make C++ work for you. • Large libraries: Since the language is used in so many applications, there's an abundance of libraries to choose from. With hundreds of open source repositories, the wealth of information (and the support systems that come with it) is vast. C++ is a double-edged sword, however, and as the famous saying goes, "With great power comes great responsibility". C++ gives you enough room to do great things, but also to get yourself into trouble if used incorrectly. Bjarne himself once said of the language, "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off." That's not to say by any means that C++ should be avoided, just that it should be used deliberately and with consideration—something the following chapter will impart.

Anatomy of a C++ Application With a brief understanding of the history of the language, we're going to start our journey by delving into a basic C++ program to see what we're working with. There's no more fitting a start than Hello World!. This famous program prints the words Hello World! to the console, and has served as the starting point for scores of programmers before you. While basic, it contains all the key components of a C++ application, so will prove a great example for us to de-construct and learn from.

4 | Your First C++ Application Let's start by taking a look at the program in its entirety: // Hello world example. #include int main() {     std::cout > myVar2;

To avoid our strings being cut off when a terminating character, such as space, is encountered, we can pull the entirety of the users input into a single variable by using the getline function. Let's update our code using this function to get the user's name:     std::cout