C++ Primer, 5th Edition

Chapter 1 – Getting Started

1.1 Writing a Simple C++ Program
  • Every C++ program must have a main function
1.2 A First Look at Input/Output
  • C++ includes an extensive standard library
  • Print text using: std::cout << “Enter two numbers:” << std::endl;
  • std::endl is called a manipulator, ends the current line and flushes the buffer, always use std::endl when debugging
  • std::cout uses the scope operator, :: , to say we want to use the name cout that’s defined in the namespace std
  • Initializing a variable means giving a value right away, int v1 = 0;
1.4 Flow Control
  • while loop repeatedly executes until false
  • for loop initializes a variable and then repeatedly executes until finished
  • while (std::cin >> value) continues reading input until invalid, like if we gave a string input when value should be integer
  • if (std::cin >> currVal) ensures input is not empty, if the read succeeds then runs body
1.5 Introducing Classes
  • Define our own data structure using a class
  • Can declare as any type, a Sales_item class can be used to declare objects of type Sales_item
  • Classes define behavior, defines all actions that be done by objects of that class
  • Headers from the standard library are enclosed in brackets <>, others are enclosed in quotes “”
  • A member function is a function defined in a class, aka methods

Part I: The Basics

Chapter 2 – Variables and Basic Types

2.1 Primitive Built-in Types
  • C++ is a statically typed language; type checking is done at compile time rather than at run time like Python
  • The smallest chunk of addressable memory is a byte, which contains 8 bits
  • Unsigned number represents positive numbers and 0, while signed numbers include that and negative numbers
  • 8-bit unsigned int holds values 0 to 255, while an 8-bit signed int holds values from -127 to 128
  • Assigning an int to a bool results in false if the value is 0, otherwise is true
  • Assigning a bool to an int results in 0 if false, otherwise is 1 if true
  • ‘A’ represents a single character while “A” represents an array of two characters, the letter ‘A’ and the null character ‘\0’
2.2 Variables
  • Initialization happens when a variable is given a value when created
  • Assignment removes the variable’s current value and replaces
  • Variables defined outside of a function are initialized to zero, but inside a function are uninitialized
  • A variable declaration specifies the type and name
  • A variable definition is a declaration, a definition also allocates storage and may provide the variable with an initial value
  • extern int i; declares but not defines, but int j; declares and defines
  • Use the scope operator (::) to access a variable globally and override the current scope
2.3 Compound Types
  • A type that is defined in terms of another type
  • A reference is an alternative name for an object, refers to another type
  • e.g. int num= 1024; then doing int &refNum = value; means that refNum refers to (another name for) num
  • A reference is not an object, but rather another name for an existing object
  • Pointers can be assigned and copied, and unlike references, are an object and don’t need to be initialized
  • Pointer holds the address of another object, int *p = &num; means p holds address of num, p is a pointer to num
  • Doing *p = 0; assigns a new value to num through p
  • pi = &ival; means a new value is assigned to pi while *pi = 0; means value that pi points is changed
  • If int ival = 1024; then int *pi = &ival; means pi points to an int and int **ppi = *pi; means ppi points to a pointer to an int
2.4 const Qualifier
  • Can’t change the value of a const object
  • To share a const object across multiple files, you must define the variable as extern
  • You can have references and pointers using const
  • Use constexpr for variables that will be used as constant expressions
2.5 Dealing with Types
  • Writing typedef double wages; means wages becomes a synonym for double
  • An alias declaration starts with the keyword using , like using SI = Sales_item; and acts as a synonym too
  • Use auto to let the compiler figure out what type to choose
2.6 Defining Our Own Data Structures
  • Use a struct to define a class and the members of the class

Chapter 3 – Strings, Vectors, and Arrays

3.1 Namespace using Declarations
  • To prevent writing std::cin each time, you can write as just cin by typing using std::cin; at the top of your file
  • Can write using namespace std; to not have to write std at all
3.2 Library string Type
  • A string is a variable-length sequence of characters, have to do #include <string>
  • String literals are not the same as the standard library strings
  • A string literal is an array of characters with a null ‘\0’ character at the end, just writing “Hello”
  • The standard library declares a string like string s = “Hello”;
  • You can add (concatenate) a string from the library and a literal, but can’t add two literals
3.3 Library vector Type
  • A vector is a collection of objects that have the same type, every object has an index so the vector is like a container
  • A vector is a class template, and templates are instructions to the compiler for generating classes or functions
  • Must have #include <vector> , and to declare a vector that holds integers you do vector<int> ivec;
  • Use ivec.push_back(10); to add the number 10 to the vector, vectors can efficiently add elements during run time
3.4 Introducing Iterators
  • Iterators fetch elements in a container, and have operations to move from one element to another
  • Iterators have members called begin and end, begin returns first element and end returns one past the end
  • When dereferencing an iterator, we get the object that the iterator denotes
  • Assuming it is an iterator into a vector of strings, check whether the string is empty by doing (*it).empty();
  • The parenthesis are necessary so that the method is called on the resulting object, can also write as it->empty();
3.5 Arrays
  • Arrays are similar to vectors, but have a fixed size and cannot have elements added to them
  • Character arrays can be initialized using a string, but must have +1 space for the null character
  • If you have an array string nums[] then string *p = nums; points to the first element in the array
  • You can do ++p; and then p points to the next element in the array
  • Arrays can have a begin and end like an iterator by declaring as int *beg = begin(array); or int *last = end(array);
  • For most applications, better to use library strings rather than C-style strings
3.6 Multidimensional Arrays
  • A multidimensional array is an array of arrays, int ia[3][4]; means array of size 3, each element is an array of size 4
  • Writing is int *ip[4]; an array of pointers to int and int (*ip)[4]; is a pointer to an array of four ints

Chapter 4 – Expressions

4.1 Fundamentals
  • Unary operators like *(dereference) and & act on one operand while binary operators like == and *(multiplication) act on two operands
  • When writing compound expressions, useful to parenthesize expressions to group the logic
4.2 Arithmetic Operators
  • The % operator is the modulus operator, calculates the remainder of division between two numbers
4.5 Increment and Decrement Operators
  • Incrementing (++) and decrementing (–) operators come in prefix and postfix form
  • If i = 0, then doing j = ++i; makes j = 1 and i = 1 but doing j = i++; makes j = 0 and i = 1
  • Prefix yields the incremented value while postfix yields the unincremented value
4.7 The Conditional Operator
  • The conditional operator (?:) does simple if-else logic,
  • string finalgrade = (grade < 60) ? “fail” : “pass”; means if true then “fail” and if false then “pass”
4.8 The Bitwise Operators
  • Recommended to use only unsigned types with bitwise operators
  • The operators are NOT (~), left shift (<<), right shift (>>), AND (&), OR (|), and XOR (^)

Chapter 5 – Statements

5.1 Simple Statements
  • A null statement is one that only contains a semicolon, useful for when the syntax requires a statement but the logic does not
5.2 Statement Scope
  • Variables defined inside a loop are only visible within that statement
5.4 Iterative Statements
  • Variables defined in a while condition or while body are created and destroyed on each iteration
5.5 Jump Statements
  • A break statement exits the loop
  • A continue statement terminates the current iteration and begins the next one

Chapter 6 – Functions

6.1 Function Basics
  • A function calls initializes the function’s parameters and transfers control to that function
  • Execution of the calling function is suspended
  • A local static variable is initialized before the first time execution, they are not destroyed when the function ends
6.2 Argument Passing
  • Passing arguments by value means that the argument value is copied and no changes are made to the original
  • Passing by reference allow a function to change the value of the original argument
  • We can use references to avoid copying if the parameter is large
  • When passing an array to a function, we are actually passing a pointer to the array’s first element
6.3 Return Types and the return Statement
  • A return statement terminates the function that is currently executing and returns control to where the function was called
  • Cannot return a local object in a function, make sure a preexisting object is returned
6.4 Overloaded Functions
  • Functions that have the same name but different parameter lists that appear in the same scope are overloaded
6.5 Features for Specialized Uses
  • Functions can have default arguments, where the given value of a parameter is constant

Chapter 7 – Classes

7.1 Defining Abstract Data Types
  • Classes define how objects of their type can be initialized through a constructor
  • Constructors are functions with the same name as the class
  • Data abstraction is the ability to define both data and function members
7.2 Access Control and Encapsulation
  • Encapsulation protects class members from general access
  • public members of a class are accessible to all parts of the program
  • private members are accessible by the functions of the class
  • The only difference between a class (can make members private) and a struct (all members public) is the default access level
7.6 static Class Members
  • Used when classes need members associated with that class, not with each individual object of that class type