\documentclass[11pt,fancy,authoryear]{elegantbook}

\title{C++ in Detail}
\subtitle{An in-depth guide to C++ on x86 systems with GCC}

\author{Nick Green}
\institute{CoffeeBeforeArch}
\date{December 31, 2020}
\version{0.0}
%\bioinfo{Bio}{Information}

%\extrainfo{Victory won\rq t come to us unless we go to it. }

%\logo{logo-blue.png}
\cover{cover.jpg}

\begin{document}

\maketitle

\frontmatter
\tableofcontents

\mainmatter

\chapter{Introduction}

From databases and web browsers to operating systems and compilers, C++ can be found almost everywhere. This along with a incredibly active community makes it a great time to start learning C++!

\section{Why This Book on C++?}

Out of all the great books on C++, why should you pick this one? Here is a list of reasons!

\begin{itemize}
  \item \textbf{It's free:} This is book (and its source) will always be free to download
  \item \textbf{It can be updated:} Printed books can not be updated. With a digital book, I can make modifications as new standards of C++ get approved, or correct errors in the text.
  \item \textbf{It fills in a gap left by other books:} Many entry level books focus solely on the C++ language, and avoid talking about implementation-specific details. This book breaks this mold by discussing these details which can be increadibly imprortant in practice.
\end{itemize}

\section{Intended Audience}

This book was written as a companion piece to my YouTube series \textbf{C++ Crash Course}. As such, the intended audience is expected to have no prior background in C++ programming.

Having some knowledge of basic programming concepts (e.g., types, functions, etc.) would be useful.

\section{Environment}

\begin{itemize}
  \item \textbf{Operating System: } Ubuntu 20.04
  \item \textbf{Compiler: } GCC 10.2
  \item \textbf{Processor: } Intel x86\-64
\end{itemize}

\section{About the Author}

My name is Nick, and I'm a computer systems architect working on deep learning accelerator performance in the San Francisco Bay Area.

My start in programming came during my undergraduate degree in electrical engineering where I took \textit{Engineering Programming with C}. While I enjoyed this course, I did not take any more dedicated programming classes during this degree (although I did some basic MATLAB and Python programming as required by various coursework).

My start with C++ came during my Ph.D. (incomplete), where I used and developed the GPGPU architecture simulator, GPGPU-Sim. This simulator (largely written in C++), was where I spent a large portion of my time.

After approximately one year of writing C-like C++, I decided to take C++ programming more seriously. There was no single book or resource I used to learn the language. Instead, I would run across a piece of C++ I didn't understand (something like a container or template), search the internet to see out how it worked, then write a minimal example to solidify my understanding. These minimal examples are what eventually became my YouTube series \textbf{C++ Crash Course}.

From then on, C++ and high performance software became one of my passions. I began writing benchmarks in C++, writing blog posts, and doing teaching livestreams.

\chapter{Foundation}

Before we dive into code samples, we need to first discuss some of the foundational parts of C++. This includes the compiler, type system, and functions. It is important to start our journey here, because the compiler, types, and functions play a role in every C++ program.

\section{The Compiler}

Processors can not directly read/execute high-level C++ code. It first must be translated into the instructions that the processor can understand (the processor's instruction set). This is done with another program known as the compiler.

The purpose of the compiler is to translate code in some source language into a target language. For the majority of examples in this book, we will focus on using the compiler to translate source code written in C++, to machine code that can execute on an x86 processor.

\section{The C++ Type System}

At the lowest level, every part of a program (from the instructions to the data) is composed of bits. How we interpret those bits is determined by types. Types in C++ fall into two categories: fundamental types, and compound types.

\subsection{Fundamental Types}

Fundamental types (sometimes referred to as built-in types) are those types are are built into the compiler, and do not require the inclusion of any other source files to use. These can be broken into the void type, integral types, and floating-point types.

\subsubsection{The Void Type}

Void is a type with an empty set of values. This means that no value can be of the void type. As no value can be of type void, what is it used for? 

In practice, void is used to express a lack of data (e.g., to express no data is returned from or passed to a function).

\subsubsection{The Boolean Type}

The boolean type, \lstinline{bool}, is capable of holding one of two values: \lstinline{true} and lstinline{false}.

\subsubsection{Integral Types}

Integral types are used to represent whole numbers that can be either signed (positive or negative) or unsigned (only positive). The basic form of this type is the \lstinline{int}.

\subsubsection{Floating-Point Types}

Floating-point types are used to represent decimal numbers according to the IEEE-754 floating point standard. The two core types in this category are \lstinline{float} (32-bits) and \lstinline{double} (64-bits).

\subsection{Compound Types}

All types that are not categorized as fundamental are considered to be compound types. According to the C++ standard, compound types can be constructed in the following ways:

\begin{itemize}
  \item Arrays of objects of a given type
  \item Functions which have parameters of given types and return void or references or objects of a given type
  \item Pointers to cv void or objects or functions (including static members of classes) of a given type
  \item References to objects or functions of a given type
  \item Classes
  \item Unions
  \item Enumerations
  \item Pointers to non-static class members
\end{itemize}

Two intuitive ways we can think about compound types are based on where the type comes from, and what they are made of. Compound types are often user-defined (i.e. not built into the compiler). For example, we can make custom types using structs and classes.

Compound types are also typically built on other types. For example, \lstinline{int} is a fundamental type, but when we take the address of that integer (where it exists in memory), we get a pointer to an integer (a compound type, based on the fundamental type \lstinline{int}).

\section{Functions}

Functions allow us to associate a name with a sequence of statements. In this section, we'll be looking at the basic structure of functions in C++, and the special case of functions called \lstinline{main}.

\subsection{Core Parts of Functions}

At their core, a function has four parts:

\begin{itemize}
  \item A return type - The type of value returned by the functions
  \item A name - Used as an identifier for the function
  \item A comma-separated parameter list - The types and names of values we want to pass to the function
  \item A function body - The set of statements this function executes
\end{itemize}

Here is a simple function we can use as an example:

\begin{lstlisting}[language=C++]
int myFunction(int a) {
  return a;
}
\end{lstlisting}

If we break this down into the core parts of the function, we have:

\begin{itemize}
  \item The return type - \lstinline{int}
  \item The name - \lstinline{myFunction}
  \item The parameter \lstinline{int a}
  \item The function body \lstinline{return a;}
\end{itemize}

\subsection{The Main Function}

Every program in both C and C++ requires a function named \lstinline{main}. The \lstinline{main} function is special because it is the entry point for our program (where execution begins when we run our executable). It also comes in two signatures.

The first function signature is what we will primarily use in this book:

\begin{lstlisting}[language=C++]
int main() {
  return 0;
}
\end{lstlisting}

This version of \lstinline{main} returns an \lstinline{int} and does not take any arguments. The return value from \lstinline{main} (\lstinline{0} in this case) is used to signal that our program completed successfully (with a non-zero value meaning some sort of error occured). \lstinline{main} is also unique in the fact that we can omit the \lstinline{return} statement from our function, and it will by defualt perform \lstinline{return 0;}.

The second form of \lstinline{main} is when we want to pass input values to our program:

\begin{lstlisting}[language=C++]
int main(int argc, char *argv){
  return 0;
}
\end{lstlisting}

The only major difference in this form of \lstinline{main} is that it has two parameters:

\begin{itemize}
  \item \lstinline{int argc} - The number of arguments
  \item \lstinline{char *argv[]} - The arguments stored as strings in an array
\end{itemize}

For the majority of this series we will be using the first form of the \lstinline{main} function.

\chapter{Basics}

Before we can write complex software, we have to master the basics. In this chapter, we will cover writing, compiling and executing C++ code, the classical "Hello world!" example, and how to work with variables in C++.

\begin{introduction}
  \item Basic C++
  \item Hello World!
  \item Working with Variables
\end{introduction}

\section{Basic C++}

\subsection{The Most Simple C++ Program}

The most simple program we can write in C++ is a one that does absolutely nothing! For this we us an empty \lstinline{main} function.

\begin{lstlisting}[language=C++]
int main() {
  return 0;
}
\end{lstlisting}

\subsection{Compiling our Program}

Now that we have a fully formed C++ program, we need to turn it into something that we can execute. In this book, we'll be using the GNU Compiler Collection (GCC), and the compiler driver g++.

As a compiler driver, g++ drives each step of translating our high-level C++ into an executable.

\subsection{Executing our Program}

Now that we have an executable, we need to execute (run) our program.

\section{Hello World!}

Now that we know how to write, compile, and run a basic C++ program, we can start looking at more interesting programs. The first of these will be the classical "Hello, world!" program. This program prints the string "Hello, world!" to the console.

\begin{lstlisting}[language=C++]
// Prints "Hello, World!" to the console using cout
// By: Nick from CoffeeBeforeArch

// Pastes the contents of file(s) where #include is located
#include <iostream>

// All C++ program require a main functions (entry point to the program)
int main() {
  // Pass "Hello, World!" to the cout stream object
  std::cout << "Hello, World!\n";

  // Return 0 typically means we did not encounter an error
  return 0;
}
\end{lstlisting}

Lets's take some time deconstructing each part of this program.

\subsection{Comments}

Comments are lines of source code that have no impact on execution because they are ignored by our compiler. We typically use comments for two purposes:

\begin{enumerate}
  \item Documentation
  \item Temporarily disabling code
\end{enumerate}

Documentation helps make software easier to reason about. For example, comments about what a function or snippet of code can save programmers the time of having to read the entire function or snippet. Within collaborative projects, comments about who the code-owner/author make it easier to identify who to seek help from

In addition to documentation, temporarily disabling code can be useful when testing/debugging. There may be situations where we want to temporarily disable code but not delete it. Comments allow us to keep the text in the file, and tell the compiler to ignore it.

There are two ways we can write comments in C++:

\begin{enumerate}
  \item Single-line comments
  \item Block comments
\end{enumerate}

Single-line comments begin with two slashes (\lstinline{//}). Any code after the two slashes and to the end of the line will be ignored by the compiler. Our first two lines of our program are an example of this:

\begin{lstlisting}[language=C++]
// Prints "Hello, World!" to the console using cout
// By: Nick from CoffeeBeforeArch
\end{lstlisting}

Block comments allow us to comment out multiple lines without haveing to add two slashes to every line. The start of our block comment begins with \lstinline{/*}, and ends with \lstinline{*/}. Everything between these two markers will be ignored by the compiler. For example, we can re-write our comments at the top of our program as follows:

\begin{lstlisting}[language=C++]
/*
Prints "Hello, World!" to the console using cout
By: Nick from CoffeeBeforeArch
*/
\end{lstlisting}

\subsection{Include Statements and the Standard Library}

One key thing we want to avoid when programming is reinventing the wheel. One of the best ways we can do this is by making use existing libraries. One of the most important libraries in C++ is the C++ Standard Library.

The C++ Standard Library is a collection of containers, algorithms, and utilities that are part of the C++ Language Standard. However, before we can use them in our program, we must tell the compiler (more specifically the preprocessor) to fetch relevant source files. We do this through include statements.

\subsection{The cout Stream Object and Namespaces}

\subsection{Compiling and Running}

\section{Working with Variables}

Variables allow us to associate a piece of memory with a name. Defining a variable requires two parts:

\begin{enumerate}
  \item A Type
  \item A Name
\end{enumerate}

A variable's type determines how much memory will be reserved, where it can be placed in memory (its alignment), and how we can interact with that piece of memory (e.g., what operations we can perform).

The name of our variable is simply how we refer to it in our program. The name of a variable can be \textit{almost} anything. Below are the rules about variable names:

\begin{itemize}
  \item Variables names must be within 1 and 255 characters
  \item Variables must begin with a letter or underscore
  \item After the first character, the remaining characters can be letters, numbers, or underscores
  \item Variable names are case sensative
  \item Reserved words (e.g., \lstinline{return}) can not be used as a variable name
\end{itemize}

In addition to these rules, variable names may not be repeated in the same scope (curly brackets).

\chapter{Control Flow}

We don't always want to execute every line of code in our program. We often want to execute different portions of code based on values in our program. For this, we can use conditional statements, loops, and functions.

\begin{introduction}
  \item Conditional Statements
  \item Loops
  \item Functions
\end{introduction}

\section{Conditional Statements}

\subsection{If and Else Satements}

\subsection{Switch Statements}

\section{Loops}

\subsection{For Loops}

\subsection{While and Do-While Loops}

\section{Functions}

\subsection{Basics}

\subsection{Overloading}

\subsection{Templates}

\chapter{Memory}

\section{Pointers and References}

\section{Dynamic Memory Allocation}

\chapter{Objects}

\section{Classes and Structs}

\subsection{Constructors}

\subsection{Destructors}

\subsection{Copy Constructors}

\subsection{Operators}

\section{Templates}

\section{Inheritance}

\section{Polymorphism}

\chapter{STL Containers and Algorithms}

\end{document}
