0% found this document useful (0 votes)
23 views990 pages

LPA Beginning C++ Programming From Beginner To Beyond SEP2024

The document contains slides for the 'Beginning C++ Programming - From Beginner to Beyond' course on Udemy, which are provided free to students. It covers the importance of learning C++, the structure of a C++ program, the curriculum overview, and common programming errors. The course aims to equip students with foundational knowledge and practical skills in C++ programming.

Uploaded by

doliheh374
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views990 pages

LPA Beginning C++ Programming From Beginner To Beyond SEP2024

The document contains slides for the 'Beginning C++ Programming - From Beginner to Beyond' course on Udemy, which are provided free to students. It covers the importance of learning C++, the structure of a C++ program, the curriculum overview, and common programming errors. The course aims to equip students with foundational knowledge and practical skills in C++ programming.

Uploaded by

doliheh374
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 990

These are the slides for the Beginning C++ Programming - From Beginner to Beyond on Udemy.

They are provided free


of charge to all students.

More information about the course: https://lpa.dev/u1bcppp

If you have any questions of queries, please add your feedback in the Q&A section of the course on Udemy.

Best regards,

Tim Buchalka
Learn Programming Academy

BEGINNING C++ PROGRAMMING BEGINNING C++ PROGRAMMING


Slides September, 2024
Beginning C++ Programming Slides

Main Course Slides.

Beginning C++ Programming – From Beginner to Beyond


Beginning C++ Programming Slides
Welcome and Introduction to the Course
• About me
• My assumptions
• Your background
• The curriculum and Modern C++
• Practice!
• Please ask questions

BEGINNING C++ PROGRAMMING INTRODUCTION


About the Course S01-CPP-0020-1
Why Learn C++?
• Popular
• Lots of code is still written in C++
• Programming language popularity indexes
• Active community, GitHub, stack overflow

• Relevant
• Windows, Linux, Mac OSX, Photoshop, Illustrator, MySQL, MongoDB,
Game engines, more …
• Amazon, Apple, Microsoft, PayPal, Google, Facebook, MySQL, Oracle, HP, IBM, more…
• VR, Unreal Engine, Machine learning, Networking & Telecom, more…

• Powerful
• fast, flexible, scalable, portable
• Procedural and Object-oriented

• Good career opportunities


• C++ skills always in demand
• C++ = Salary++

BEGINNING C++ PROGRAMMING INTRODUCTION


Why Learn C++? S01-CPP-0040-1
Modern C++ and the C++ Standard
• Early 1970s • 1998
• C Programming Language • C++98 Standard
• Dennis Ritchie
• 2003
• 1979 • C++03 Standard
• Bjarne Stroustrup
• 2011
• C with Classes
• C++11 Standard
• 1983
• 2014
• Name changed to C++
• C++14 Standard
• 1989
• 2017
• First commercial release
• C++17 Standard

BEGINNING C++ PROGRAMMING INTRODUCTION


Modern C++ and the C++ Standard S01-CPP-0060-1
Modern C++ and the C++ Standard
• Classical C++ • Modern C++
• Pre C++11 Standard • C++11
• Lots of new features
• C++14
• Smaller changes
• C++17
• Simplification
• Best practices
• Core Guidelines

BEGINNING C++ PROGRAMMING INTRODUCTION


Modern C++ and the C++ Standard S01-CPP-0060-2
How does it all work?
• You must tell the computer EXACTLY what to do
• Program – like a recipe
• Programming language
• source code
• high-level
• for humans
• Editor – used to enter program text
• .cpp and .h files
• Binary or other low-level representation
• object code
• for computers
• Compiler – translates from high-level to low-level
• Linker – links together our code with other libraries
• Creates executable program
• Testing and Debugging – finding and fixing program errors

BEGINNING C++ PROGRAMMING INTRODUCTION


How does it all work? S01-CPP-0080-1
The C++ Build Process

BEGINNING C++ PROGRAMMING INTRODUCTION


How does it all work? S01-CPP-0080-2
Integrated Development Environments (IDEs)
•Editor •CodeLite
•Compiler •Code::Blocks
•Linker •NetBeans
•Debugger •Eclipse
•Keep everything in sync •CLion
•Dev-C++
•KDevelop
•Visual Studio
•Xcode

BEGINNING C++ PROGRAMMING INTRODUCTION


How does it all work? S01-CPP-0080-3
Section Overview
•Microsoft Windows, Mac OSX, Ubuntu Linux 18.04
•C++ Compiler
•CodeLite Integrated Development Environment (IDE)
•Configure CodeLite
•Create a Default CodeLite Project Template

•Using the Command-line

•Using a Web-based compiler

BEGINNING C++ PROGRAMMING INSTALLATION AND SETUP


Installation and Setup Overview S02-CPP-0020-1
Using the command-line interface
•A text editor (not a Word Processor)
•A command-prompt or terminal window
•An installed C++ compiler

•No need for an IDE


•Simple, efficient workflow
•Better as you gain experience
•Can be used if you are overwhelmed by IDEs
•Useful if hardware resources are limited

BEGINNING C++ PROGRAMMING INSTALLATION AND SETUP


Using the Command Line S02-CPP-0200-1
Curriculum Overview
• Getting Started • Pointers and References
• Structure of a C++ Program • OOP – Classes and Objects
• Variables and Constants • Operator Overloading
• Arrays and Vectors • Inheritance
• Strings in C++ • Polymorphism
• Expressions, Statements • Smart Pointers
and Operators
• The Standard Template Library (STL)
• Statements and Operators
• I/O Streams
• Determining Control Flow
• Exception Handling
• Functions

BEGINNING C++ PROGRAMMING CURRICULUM OVERVIEW


Curriculum Overview S03-CPP-0020-1
Curriculum Overview
Challenge Exercises
•At the end of most course sections

•Develop real C++ programs using what we discussed in the section

•Section challenges
• Description
• Starting project
• Completed solution

•Have fun and keep coding!

BEGINNING C++ PROGRAMMING CURRICULUM OVERVIEW


Challenge Exercises S03-CPP-0040-1
Curriculum Overview
Quizzes
•At the end of most sections

•Reinforce the concepts learned in each section

•Quiz style
• Multiple choice
• Fill in blank
• Concept oriented vs. code oriented

BEGINNING C++ PROGRAMMING CURRICULUM OVERVIEW


Quizzes S03-CPP-0060-1
Section Overview
• CodeLite IDE Quick Tour

• Our first program


• Building
• Running
• Errors
• Warnings

BEGINNING C++ PROGRAMMING GETTING STARTED


Section Overview S04-CPP-0020-1
Compiler Errors
• Programming languages have rules

• Syntax errors – something wrong with the structure


std::cout << “Errors << std::endl;

return 0

• Semantic errors – something wrong with the meaning


a + b; When it doesn’t make sense to add a and b

BEGINNING C++ PROGRAMMING GETTING STARTED


What are Compiler Errors? S04-CPP-0100-1
Compiler Warnings
Do NOT ignore them!

• The compiler has recognized an issue with your code that could lead to a
potential problem

• It’s only a warning because the compiler is still able to generate correct
machine code

int miles_driven;
std::cout << miles_driven;

warning: 'miles_driven' is used uninitialized …

BEGINNING C++ PROGRAMMING GETTING STARTED


What are Compiler Warnings? S04-CPP-0120-1
Linker Errors
• The linker is having trouble linking all the object files together to create an
executable

• Usually there is a library or object file that is missing

BEGINNING C++ PROGRAMMING GETTING STARTED


What are Linker Errors? S04-CPP-0140-1
Runtime Errors
• Errors that occur when the program is executing

• Some typical runtime errors


• Divide by zero
• File not found
• Out of memory

Can cause your program to ‘crash’

Exception Handling can help deal with runtime errors

BEGINNING C++ PROGRAMMING GETTING STARTED


What are Runtime Errors? S04-CPP-0160-1
Logic Errors
• Errors or bugs in your code that cause your program to run incorrectly

• Logic errors are mistakes made by the programmer

Suppose we have a program that determines if a person can vote in an election


and you must be 18 years or older to vote.

if (age > 18) {


std::cout << “Yes, you can vote!”;
}

Test your code!!

BEGINNING C++ PROGRAMMING GETTING STARTED


What are Logic Errors? S04-CPP-0180-1
Section Overview
The Structure of a C++ Program
• Basic Components
• Preprocessor Directives
• The main function
• Namespaces
• Comments
• Basic I/O

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Section Overview S05-CPP-0020-1
The Structure of a C++ Program
Components of a C++ Program
• Keywords
• Identifiers
• Operators
• Punctuation
• Syntax

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-1
Keywords
• Have special meaning in C++
• Are reserved by the C++ language

#include <iostream>

int main() {

int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;

std::cout << "No really!!, " << favorite_number << " is my favorite number!" <<std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-2
Identifiers
• Programmer-defined names
• Not part of the C++ language
• Used to name variables, functions, etc.
#include <iostream>

int main() {

int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;

std::cout << "No really!!, " << favorite_number << " is my favorite number!" <<std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-3
Operators
• Arithmetic operators, assignment, <<, >>
• Are reserved by the C++ language

#include <iostream>

int main() {

int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;

std::cout << "No really!!, " << favorite_number << " is my favorite number!" <<std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-4
Punctuation
• Special characters that separate, terminate items

#include <iostream>

int main() {

int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;

std::cout << "No really!!, " << favorite_number << " is my favorite number!" <<std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-5
Syntax
• How the programming elements are put together to form a program
• Programming languages have rules

#include <iostream>

int main() {

int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;

std::cout << "No really!!, " << favorite_number << " is my favorite number!" <<std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-6
Our Section 4 Challenge Solution
Modified slightly
• Added comments
• Using namespace instead of std::
// Preprocessor directive that include the iostream library headers
#include <iostream>

// use the std namespace


using namespace std;

/* Start of the program


* program execution always begins with main()
*/
int main() {

int favorite_number; // declare my favorite number variable

// Note that I'm no longer using std::


// Prompt the user to enter their favorite number

cout << "Enter your favorite number between 1 and 100: ";

// read the user's input into the variable favorite_number

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-7
Our Section 4 Challenge Solution
Modified slightly
// Preprocessor directive that include the iostream library headers
#include <iostream>

// use the std namespace


using namespace std;

/* Start of the program


* program execution always begins with main()
*/
int main() {

int favorite_number; // declare my favorite number variable

// Note that I'm no longer using std::


// Prompt the user to enter their favorite number

cout << "Enter your favorite number between 1 and 100: ";

// read the user's input into the variable favorite_number


cin >> favorite_number;

// Out put the results to the user


cout << "Amazing!! That's my favorite number too!" << endl;
cout << "No really!!, " << favorite_number << " is my favorite number!" << endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-8
Preprocessor Directives
• What is a preprocessor?
• What does it do?
• Directives start with ‘#’
• Commands to the preprocessor

#include <iostream>
#include “myfile.h”

#if
#elif
#else
#endif

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-9
Comments
• Ignored by the compiler
• Used to explain your code
• Two styles
int favorite_number; // This will store my favorite number

// The following lines convert Euros to US Dollars

/* This is a comment
that spans multiple lines.
All of these lines will be ignored by the compiler
*/

// Why should be have to explain our own code?

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-10
Functions
• main() is a required function in C++
• Break up your code into units of functionality
• Can optionally receive and return information

/* This is a function that expects two integers a and b


It calculates the sum of a and b and returns it to the caller
Note that we specify that the function returns an int
*/

int add_numbers(int a, int b)


{
return a + b;
}

// I can call the function and use the value that is returns

cout << add_numbers(20, 40);

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


C++ Structure Overview S05-CPP-0040-11
Preprocessor Directives
• What is a preprocessor?
• What does it do?
• Directives start with ‘#’
• Commands to the preprocessor
#include <iostream>
#include “myfile.h”

#if
#elif
#else
#endif

#ifdef
#ifndef
#define
#undef

#line
#error
#pragma

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Preprocessor Directives S05-CPP-0060-1
The main() function
• Every C++ program must have exactly 1 main( ) function
• Starting point of program execution
• return 0 indicates successful program execution
• 2 versions that are both valid
int main()
{
// code

return 0;
}

program.exe

int main(int argc, char *argv[])


{
// code

return 0;
}

program.exe argument1 argument2

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Main Function S05-CPP-0100-1
Namespaces
• Why std::cout and not just cout?
• What is a naming conflict?
• Names given to parts of code to help reduce naming conflicts
• std is the name for the C++ ‘standard’ namespace
• Third-party frameworks will have their own namespaces
• Scope resolution operator ::
• How can we use these namespaces?

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Namespaces S05-CPP-0120-1
Explicitly using namespaces
#include <iostream>

int main()
{
int favorite_number;

std::cout << "Enter your favorite number between 1 and 100: ";

std::cin >> favorite_number;

std::cout << "Amazing!! That's my favorite number too!" << std::endl;


std::cout << "No really!!, " << favorite_number
<< " is my favorite number!" << std::endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Namespaces S05-CPP-0120-2
The using namespace directive
#include <iostream>

using namespace std; // Use the entire std namespace

int main()
{
int favorite_number;

cout << "Enter your favorite number between 1 and 100: ";

cin >> favorite_number;

cout << "Amazing!! That's my favorite number too!" << endl;


cout << "No really!!, " << favorite_number
<< " is my favorite number!" << endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Namespaces S05-CPP-0120-3
Qualified using namespace variant
#include <iostream>

using std::cout; // use only what you need


using std::cin;
using std::endl;

int main()
{
int favorite_number;

cout << "Enter your favorite number between 1 and 100: ";

cin >> favorite_number;

cout << "Amazing!! That's my favorite number too!" << endl;


cout << "No really!!, " << favorite_number
<< " is my favorite number!" << endl;

return 0;
}

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Namespaces S05-CPP-0120-4
Basic I/O using cin and cout
cout, cin, cerr, and clog are objects representing streams
cout
• standard output stream
• console
cin
• standard input stream
• keyboard
<<
• Insertion operator
• output streams
>>
• extraction operator
• input streams

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Basic IO S05-CPP-0140-1
cout and <<
• Insert the data into the cout stream
cout << data;

• Can be chained
cout << "data 1 is " << data1;

• Does not automatically add line breaks


cout << "data 1 is " << data1 << endl;
cout << "data 1 is " << data1 << "\n";

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Basic IO S05-CPP-0140-2
cin and >>
• Extract data from the cin stream based on data’s type
cin >> data;

• Can be chained
cin >> data1 >> data2;

• Can fail if the entered data cannot be interpreted


data could have an undetermined value

BEGINNING C++ PROGRAMMING STRUCTURE OF A C++ PROGRAM


Basic IO S05-CPP-0140-3
Section Overview
Variables and Constants
• Declaring variables
• C++ primitive types
• integer
• floating point
• boolean
• character
• sizeof operator

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Section Overview S06-CPP-0020-1
Section Overview
Variables and Constants
• What is a constant?
• Declaring constants
• Literal constants
• Constant expressions

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Section Overview S06-CPP-0020-2
What is a variable?

move 21 to location 1002

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a variable? S06-CPP-0040-1
What is a variable?

move 21 to age

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a variable? S06-CPP-0040-2
What is a variable?
• A variable is an abstraction for a memory location
• Allow programmers to use meaningful names and not memory addresses
• Variables have
• Type – their category (integer, real number, string, Person, Account…)
• Value – the contents (10, 3.14. “Frank”…)

• Variables must be declared before they are used


• A variables value may change

int age;
age = 21; // Compiler error
age = 21;

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a variable? S06-CPP-0040-3
Declaring and Initializing Variables
Declaring Variables

VariableType VariableName;

int age;
double rate;
string name;

Account franks_account;
Person james;

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Declaring Variables S06-CPP-0060-1
Declaring and Initializing Variables
Naming Variables
•Can contain letters, numbers, and underscores

•Must begin with a letter or underscore (_)


•cannot begin with a number

•Cannot use C++ reserved keywords

•Cannot redeclare a name in the same scope


•remember that C++ is case sensitive

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Declaring Variables S06-CPP-0060-2
Declaring and Initializing Variables
Naming Variables
Legal Illegal

Age int

age $age

_age 2014_age

My_age My age

your_age_in_2014 Age+1

INT cout

Int return

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Declaring Variables S06-CPP-0060-3
Declaring and Initializing Variables
Naming Variables – Style and Best Practices
•Be consistent with your naming conventions
•myVariableName vs. my_variable_name
•avoid beginning names with underscores

•Use meaningful names


•not too long and not too short

•Never use variables before initializing them

•Declare variables close to when you need them in your code

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Declaring Variables S06-CPP-0060-4
Declaring and Initializing Variables
Initializing Variables

int age; // uninitialized


int age = 21; // C-like initialization

int age (21); // Constructor initialization

int age {21}; // C++11 list initialization syntax

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Declaring Variables S06-CPP-0060-5
C++ Primitive Data Types
• Fundamental data types implemented directly by the C++ language

• Character types
• Integer types
• signed and unsigned
• Floating-point types
• Boolean type

• Size and precision is often compiler-dependent


• #include <climits>

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-1
C++ Primitive Data Types
Type sizes
• Expressed in bits
• The more bits the more values that can be represented
• The more bits the more storage required

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-2
C++ Primitive Data Types
Character Types
• Used to represent single characters, ‘A’, ‘X’, ‘@’
• Wider types are used to represent wide character sets

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-3
C++ Primitive Data Types
Integer Types
• Used to represent whole numbers
• Signed and unsigned versions

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-4
C++ Primitive Data Types
Integer Types

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-5
C++ Primitive Data Types
Floating-point Type
• Used to represent non-integer numbers
• Represented by mantissa and exponent (scientific notation)
• Precision is the number of digits in the mantissa
• Precision and size are compiler dependent

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-6
C++ Primitive Data Types
Boolean Type
• Used to represent true and false
• Zero is false.
• Non-zero is true.

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


Primitive Types S06-CPP-0100-7
Using the sizeof operator
• The sizeof operator
• determines the size in bytes of a type or variable

• Examples:

sizeof(int)
sizeof(double)

sizeof(some_variable)

sizeof some_variable

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


sizeof S06-CPP-0120-1
Using the sizeof operator
<climits> and <cfloat>

• The climits and cfloat include files contain size and precision information about your
implementation of C++

INT_MAX
INT_MIN
LONG_MIN
LONG_MAX
FLT_MIN
FLT_MAX
. . .

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


sizeof S06-CPP-0120-2
What is a constant?
• Like C++ variables
• Have names
• Occupy storage
• Are usually typed

However, their value cannot change once declared!

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-1
Types of constants in C++
• Literal constants
• Declared constants
• const keyword
• Constant expressions
• constexpr keyword
• Enumerated constants
• enum keyword
• Defined constants
• #define

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-2
Types of constants in C++
Literal constants

• The most obvious kind of constant


x = 12;
y = 1.56;
name = “Frank”;
middle_initial = ‘J’;

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-3
Types of constants in C++
Literal constants

• Integer Literal Constants


12 - an integer
12U - an unsigned integer
12L - a long integer
12LL - a long long integer

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-4
Types of constants in C++
Literal constants

• Floating-point Literal Constants


12.1 - a double
12.1F - a float
12.1L - a long double

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-5
Types of constants in C++
Literal constants

• Character Literal Constants (escape codes)


\n - newline
\r - return
\t - tab
\b - backspace
\’ - single quote
\” - double quote
\\ - backslash

cout << “Hello\tthere\nmy friend\n”;


Hello there
my friend

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-6
Types of constants in C++
Declared constants

• Constants declared using the const keyword

const double pi {3.1415926};

const int months_in_year {12};

pi = 2.5; // Compiler error

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-7
Types of constants in C++
Defined constants

• Constants declared using the const keyword

#define pi 3.1415926

Don’t use defined constants in Modern C++

BEGINNING C++ PROGRAMMING VARIABLES AND CONSTANTS


What is a Constant? S06-CPP-0140-8
Section Overview
Arrays and Vectors
•Arrays
•What they are
•Why we use arrays
•Declaration and initialization
•Accessing array elements
•Multi-dimensional arrays
•Vectors
•What they are
•Advantages vs. arrays
•Declaration and initialization

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
S07-CPP-0020-1
Section Overview
Arrays
What is an array?
•Compound data type or data structure
•Collection of elements
•All elements are of the same type
•Each element can be accessed directly

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
S07-CPP-0040-1
What is an Array?
Arrays
Why do we need arrays?

int test_score_1 {0};


int test_score_2 {0};
int test_score_3 {0};

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
S07-CPP-0040-2
What is an Array?
Arrays
Why do we need arrays?

int test_score_1 {0};


int test_score_2 {0};
int test_score_3 {0};
int test_score_4 {0};
int test_score_5 {0};
. . .
int test_score_100 {0};
ARRAYS AND VECTORS
BEGINNING C++ PROGRAMMING
S07-CPP-0040-3
What is an Array?
Arrays
Characteristics
•Fixed size
•Elements are all the same type
•Stored contiguously in memory
•Individual elements can be accessed by
•their position or index

•First element is at index 0


•Last element is at index size-1

•No checking to see if you are out of bounds

•Always initialize arrays


•Very efficient
•Iteration (looping) is often used to process

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
S07-CPP-0040-4
What is an Array?
Arrays
Declaring

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Declaring and Initializing Arrays S07-CPP-0060-1
Arrays
Initialization

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Declaring and Initializing Arrays S07-CPP-0060-2
Arrays
Accessing array elements

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Accessing Array Elements S07-CPP-0080-1
Arrays
Changing the contents of array elements

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Accessing Array Elements S07-CPP-0080-2
Arrays
How does it work?

•The name of the array represent the location of the first element in the
array (index 0)

•The [index] represents the offset from the beginning of the array

•C++ simply performs a calculation to find the correct element

•Remember – no bounds checking!

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Accessing Array Elements S07-CPP-0080-3
Arrays
Declaring multi-dimensional arrays

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Multidimensional Arrays S07-CPP-0100-1
Arrays
Multi-dimensional arrays

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Multidimensional Arrays S07-CPP-0100-2
Arrays
Accessing array elements in multi-dimensional arrays

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Multidimensional Arrays S07-CPP-0100-3
Arrays
Initializing multi-dimensional arrays

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
Multidimensional Arrays S07-CPP-0100-4
Vectors
•Suppose we want to store test scores for my school

•I have no way of knowing how many students will register next year
•Options:
•Pick a size that you are not likely to exceed and use static arrays
•Use a dynamic array such as vector

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-1
Vectors
What is a vector?

•Container in the C++ Standard Template Library

•An array that can grow and shrink in size at execution time

•Provides similar semantics and syntax as arrays

•Very efficient

•Can provide bounds checking

•Can use lots of cool functions like sort, reverse, find, and more.
ARRAYS AND VECTORS
BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-2
Vectors
Declaring

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-3
Vectors
Declaring

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-4
Vectors
Initializing

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-5
Vectors
Characteristics
•Dynamic size
•Elements are all the same type
•Stored contiguously in memory
•Individual elements can be accessed by
•their position or index

•First element is at index 0


•Last element is at index size-1

•[ ] - no checking to see if you are out of bounds


•Provides many useful function that do bounds check

•Elements initialized to zero


•Very efficient
•Iteration (looping) is often used to process

ARRAYS AND VECTORS


BEGINNING C++ PROGRAMMING
What is a Vector? S07-CPP-0120-6
Vectors
Accessing vector elements – array syntax

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Accessing and Modifying Vector elements S07-CPP-0140-1
Vectors
Accessing vector elements – vector syntax

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Accessing and Modifying Vector elements S07-CPP-0140-2
Vectors
Changing the contents of vector elements – vector syntax

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Accessing and Modifying Vector elements S07-CPP-0140-3
Vectors
So, when do they grow as needed?

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Accessing and Modifying Vector elements S07-CPP-0140-4
Vectors
What if you are out of bounds?
•Arrays never do bounds checking
•Many vector methods provide bounds checking
•An exception and error message is generated

BEGINNING C++ PROGRAMMING ARRAYS AND VECTORS


Accessing and Modifying Vector elements S07-CPP-0140-5
Section Overview
Expressions, Statements and Operators
• Expressions
• Statements and block statements
• Operators
• Assignment

• Arithmetic

• Increment and decrement

• Equality

• Relational

• Logical

• Compound assignment

• Precedence

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Section Overview S08-CPP-0020-1
Expressions and Statements
Expressions
An expression is:
•The most basic building block of a program
•“a sequence of operators and operands that specifies a computation”
•Computes a value from a number of operands
•There is much, much more to expressions – not necessary at this level

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Expressions and Statements S08-CPP-0040-1
Expressions and Statements
Expressions - examples

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Expressions and Statements S08-CPP-0040-2
Expressions and Statements
Statements
A statement is:
•A complete line of code that performs some action
•Usually terminated with a semi-colon
•Usually contain expressions
•C++ has many types of statements
•expression, null, compound, selection, iteration,
•declaration, jump, try blocks, and others.

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Expressions and Statements S08-CPP-0040-3
Expressions and Statements
Statements - examples

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Expressions and Statements S08-CPP-0040-4
Using Operators
• C++ has a rich set of operators

• unary, binary, ternary

• Common operators can be grouped as follows:


• assignment
• arithmetic
• increment/decrement
• relational
• logical
• member access
• other

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Using Operators S08-CPP-0060-1
Assignment Operator (=)
lhs = rhs
•rhs is an expression that is evaluated to a value
•The value of the rhs is stored to the lhs

•The value of the rhs must be type compatible with the lhs
•The lhs must be assignable

•Assignment expression is evaluated to what was just assigned


•More than one variable can be assigned in a single statement

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Assignment Operator (=) S08-CPP-0080-1
Mixed Type Expressions
•C++ operations occur on same type operands

•If operands are of different types, C++ will convert one

•Important! since it could affect calculation results


•C++ will attempt to automatically convert types (coercion).

If it can’t, a compiler error will occur

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Mixed Type Expressions S08-CPP-0140-1
Mixed Type Expressions
Conversions
•Higher vs. Lower types are based on the size of the values the type can hold
•long double,double,float,unsigned long,long,unsigned int,int
•short and char types are always converted to int
•Type Coercion: conversion of one operand to another data type
•Promotion: conversion to a higher type
•Used in mathematical expressions
•Demotion: conversion to a lower type
•Used with assignment to lower type

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Mixed Type Expressions S08-CPP-0140-2
Mixed Type Expressions
Examples

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Mixed Type Expressions S08-CPP-0140-3
Mixed Type Expressions
Explicit Type Casting – static_cast<type>

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Mixed Type Expressions S08-CPP-0140-4
Testing for Equality
The == and != operators
•Compares the values of 2 expressions
•Evaluates to a Boolean (True or False, 1 or 0)
•Commonly used in control flow statements

expr1 == expr2

expr1 != expr2

100 == 200
num1 != num2
STATEMENTS AND OPERATORS
BEGINNING C++ PROGRAMMING
Testing for Equality S08-CPP-0160-1
Testing for Equality
The == and != operators

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Testing for Equality S08-CPP-0160-2
Relational Operators

expr1 op expr2

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Relational Operators S08-CPP-0180-1
Logical Operators

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-1
Logical Operators
not (!)

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-2
Logical Operators
and (&&)

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-3
Logical Operators
or (||)

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-4
Logical Operators
Precedence
•not has higher precedence than and
•and has higher precedence than or

•not is a unary operator


•and and or are binary operators

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-5
Logical Operators
Examples

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-6
Logical Operators
Short-Circuit Evaluation
•When evaluating a logical expression C++ stops as soon as the
result is known

expr1 && expr2 && expr3

expr1 || expr2 || expr3

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Logical Operators S08-CPP-0200-7
Compound Assignment
op=

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Compound Assignment S08-CPP-0220-1
Logical Operators
Examples

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Compound Assignment S08-CPP-0220-2
Operator Precedence (not a complete list)
Higher to lower

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Operator Precedence S08-CPP-0240-1
Operator Precedence
What is associativity?
•Use precedence rules when adjacent operators are different

expr1 op1 expr2 op2 expr3 // precedence

•Use associativity rules when adjacent operators have the same


precedence

expr1 op1 expr2 op1 expr3 // associativity

•Use parenthesis to absolutely remove any doubt

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Operator Precedence S08-CPP-0240-2
Operator Precedence
Example

STATEMENTS AND OPERATORS


BEGINNING C++ PROGRAMMING
Operator Precedence S08-CPP-0240-3
Section Overview
Controlling Program Flow

• Sequence
• Ordering statements sequentially
• Selection
• Making decisions
• Iteration
• Looping or repeating

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Section Overview S09-CPP-0020-1
Selection – Decision Making
• if statement
• if-else statement
• Nested if statements
• switch statement
• Conditional operator ?:

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Section Overview S09-CPP-0020-2
Iteration - Looping
• for loop
• Range-based for loop
• while loop
• do-while loop
• continue and break
• Infinite loops
• Nested loops

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Section Overview S09-CPP-0020-3
if statement

if (expr)
statement;

• If the expression is true then execute the statement

• If the expression is false then skip the statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if Statement S09-CPP-0040-1
if statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if Statement S09-CPP-0040-2
if statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if Statement S09-CPP-0040-3
if statement
block statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if Statement S09-CPP-0040-4
Block statement

• Create a block of code by including more than one statement in code block { }
• Blocks can also contain variable declarations
• These variables are visible only within the block – local scope

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if Statement S09-CPP-0040-5
if-else statement

• If the expression is true then execute statement1

• If the expression is false then execute statement2

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if else Statement S09-CPP-0060-1
if-else statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if else Statement S09-CPP-0060-2
if-else statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if else Statement S09-CPP-0060-3
if-else statement
block statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if else Statement S09-CPP-0060-4
if-else-if construct
block statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


if else Statement S09-CPP-0060-5
Nested if statement

•if statement is nested within another

•Allows testing of multiple conditions

•else belongs to the closest if

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested if Statement S09-CPP-0080-1
Nested if statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested if Statement S09-CPP-0080-2
Nested if statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested if Statement S09-CPP-0080-3
Nested if statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested if Statement S09-CPP-0080-4
The switch statement

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


switch-case statement S09-CPP-0100-1
The switch statement
example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


switch-case statement S09-CPP-0100-2
The switch statement
fall-through example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


switch-case statement S09-CPP-0100-3
The switch statement
with an enumeration

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


switch-case statement S09-CPP-0100-4
The switch statement
•The control expression must evaluate to an integer type

•The case expressions must be constant expressions that evaluate to


integer or integers literals

•Once a match occurs all following case sections are executes UNTIL a
break is reached the switch complete

•Best practice – provide break statement for each case


•Best practice – default is optional, but should be handled

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


switch-case statement S09-CPP-0100-5
Conditional Operator
?:

• cond_expr evaluates to a boolean expression

• If cond_expr is true then the value of expr1 is returned


• If cond_expr is false then the value of expr2 is returned

• Similar to if-else construct


• Ternary operator
• Very useful when used inline
• Very easy to abuse!

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Conditional Operator S09-CPP-0120-1
Conditional Operator
example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Conditional Operator S09-CPP-0120-2
Looping
iteration

• The third basic building block of programming


• sequence, selection, iteration

• Iteration or repetition

• Allows the execution of a statement or block of statements repeatedly

• Loops are made up a loop condition and the body which contains the
statements to repeat

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Looping S09-CPP-0140-1
Looping
Some typical use-cases

Execute a loop:
• a specific number of times
• for each element in a collection
• while a specific condition remains true
• until a specific condition becomes false
• until we reach the end of some input stream
• forever
• many, many more

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Looping S09-CPP-0140-2
C++ Looping Constructs
• for loop
• iterate a specific number of times

• Range-based for loop


• one iteration for each element in a range or collection

• while loop
• iterate while a condition remains true
• stop when the condition becomes false
• check the condition at the beginning of every iteration

• do-while loop
• iterate while a condition remains true
• stop when the condition becomes false
• check the condition at the end of every iteration

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Looping S09-CPP-0140-3
for Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-1
for Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-2
for Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-3
for Loop
display even numbers

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-4
for Loop
array example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-5
for Loop
comma operator

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-6
for Loop
some other details…

• The basic for loop is very clear and concise


• Since the for loop’s expressions are all optional, it is possible to have
• no initialization
• no test
• no increment

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


for Loop S09-CPP-0160-7
Range-based for Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-1
Range-based for Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-2
Range-based for Loop
auto

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-3
Range-based for Loop
vector

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-4
Range-based for Loop
initializer list

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-5
Range-based for Loop
string

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Ranged-based for Loop S09-CPP-0180-6
while Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-1
while Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-2
while Loop
even numbers

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-3
while Loop
array example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-4
while Loop
input validation

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-5
while Loop
input validation

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-6
while Loop
input validation – boolean flag

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


while Loop S09-CPP-0200-7
do-while Loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


do-while Loop S09-CPP-0220-1
do-while Loop
input validation

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


do-while Loop S09-CPP-0220-2
do-while Loop
area calculation with calculate another

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


do-while Loop S09-CPP-0220-3
continue and break statements
• continue
• no further statements in the body of the loop are executed
• control immediately goes directly to the beginning of the loop for the next
iteration

• break
• no further statements in the body of the loop are executed
• loop is immediately terminated
• Control immediately goes to the statement following the loop construct

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


continue and break statements S09-CPP-0240-1
continue and break statements

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


continue and break statements S09-CPP-0240-2
Infinite Loops
• Loops whose condition expression always evaluate to true

• Usually this is unintended and a programmer error

• Sometimes programmers use infinite loops and include


and break statements in the body to control them

• Sometimes infinite loops are exactly what we need


• Event loop in an event-driven program
• Operating system

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Infinite Loops S09-CPP-0260-1
Infinite for Loops

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Infinite Loops S09-CPP-0260-2
Infinite while Loops

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Infinite Loops S09-CPP-0260-3
Infinite do-while Loops

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Infinite Loops S09-CPP-0260-4
Infinite while Loops
example

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Infinite Loops S09-CPP-0260-5
Nested Loops
• Loop nested within another loop

• Can be many as many levels deep as the program needs

• Very useful with multi-dimensional data structures

• Outer loop vs. Inner loop

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-1
Nested Loops

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-2
Nested Loops
Multiplication Table

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-3
Nested Loops
2D Arrays – set all elements to 1000

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-4
Nested Loops
2D Arrays – display elements

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-5
Nested Loops
2D Vector – display elements

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Nested Loops S09-CPP-0280-6
Section Overview
Characters and Strings

• Character functions

• C-style Strings

• Working with C-style Strings

• C++ Strings

• Working with C++ Strings

BEGINNING C++ PROGRAMMING CONTROLLING PROGRAM FLOW


Section Overview S10-CPP-0020-1
Character Functions
#include <cctype>

• Functions for testing characters

• Functions for converting character case

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


Character Functions S10-CPP-0040-1
Character Functions
Testing characters

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


Character Functions S10-CPP-0040-2
Character Functions
Converting characters

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


Character Functions S10-CPP-0040-3
C-style Strings
•Sequence of characters
•contiguous in memory
•implemented as an array of characters
•terminated by a null character (null)
• null – character with a value of zero
•Referred to as zero or null terminated strings

•String literal
•sequence of characters in double quotes, e.g. “Frank”
•constant
•terminated with null character

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-1
C-style Strings

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-2
C-style Strings
declaring variables

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-3
C-style Strings
declaring variables

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-4
C-style Strings
declaring variables

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-5
#include <cstring>
Functions that work with C-style Strings

•Copying

•Concatenation

•Comparison

•Searching

•and others

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-6
#include <cstring>
A few examples

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-7
#include <cstdlib>
General purpose functions

•Includes functions to convert C-style Strings to

•integer
•float
•long
•etc.

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C-style Strings S10-CPP-0060-8
C++ Strings
•std::string is a Class in the Standard Template Library
•#include <string>
•std namespace
•contiguous in memory
•dynamic size
•work with input and output streams
•lots of useful member functions
•our familiar operators can be used (+, = , < , <=, >, >=, +=, ==, !=, []…)
•can be easily converted to C-style Strings if needed
•safer

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-1
C++ Strings
Declaring and initializing

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-2
C++ Strings
Assignment =

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-3
C++ Strings
Concatenation

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-4
C++ Strings
Accessing characters [] and at() method

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-5
C++ Strings
Accessing characters [] and at() method

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-6
C++ Strings
Accessing characters [] and at() method

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-7
C++ Strings
Comparing
== != > >= < <=

The objects are compared character by character lexically.

Can compare:
two std::string objects
std::string object and C-syle string literal
std::string object and C-style string variable

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-8
C++ Strings
Comparing

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-9
C++ Strings
Substrings – substr()

Extracts a substring from a std::string

object.substr(start_index, length)

string s1 {"This is a test"};

cout << s1.substr(0,4); // This


cout << s1.substr(5,2); // is
cout << s1.substr(10,4); // test

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-10
C++ Strings
Searching – find()

Returns the index of a substring in a std::string

object.find(search_string)

string s1 {"This is a test"};

cout << s1.find("This"); // 0


cout << s1.find("is"); // 2
cout << s1.find("test"); // 10
cout << s1.find('e'); // 11
cout << s1.find("is", 4); // 5
cout << s1.find("XX"); // string::npos

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-11
C++ Strings
Removing characters – erase() and clear()

Removes a substring of characters from a std::string

object.erase(start_index, length)

string s1 {"This is a test"};

cout << s1.erase(0,5); // is a test


cout << s1.erase(5,4); // is a
s1.clear(); // empties string s1

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-12
C++ Strings
Other useful methods

string s1 {"Frank"};

cout << s1.length() << endl; // 5

s1 += " James";
cout << s1 << endl; // Frank James

Many more…

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-13
C++ Strings
Input >> and getline()

Reading std::string from cin

string s1;
cin >> s1; // Hello there
// Only accepts up to the first space
cout << s1 << endl; // Hello

getline(cin, s1); // Read entire line until \n


cout << s1 << end; // Hello there

getline(cin, s1, 'x'); // this isx


cout << s1 << endl; // this is

BEGINNING C++ PROGRAMMING CHARACTERS AND STRINGS


C++ Strings S10-CPP-0100-14
Functions
• Function
• definition
• prototype
• Parameters and pass-by-value
• return statement
• default parameter values
• overloading
• passing arrays to function
• pass-by-reference
• inline functions
• auto return type
• recursive functions

BEGINNING C++ PROGRAMMING FUNCTIONS


Section Overview S11-CPP-0020-1
What is a function?
•C++ programs
•C++ Standard Libraries (functions and classes)
•Third-party libraries (functions and classes)
•Our own functions and classes

•Functions allow the modularization of a program


•Separate code into logical self-contained units
•These units can be reused

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-1
What is a function?

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-2
What is a function?

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-3
What is a function?
Boss/Worker analogy
•Write your code to the function specification
•Understand what the function does
•Understand what information the function needs
•Understand what the function returns
•Understand any errors the function may produce
•Understand any performance constraints

•Don’t worry about HOW the function works internally


•Unless you are the one writing the function!

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-4
What is a function?
Example <cmath>
•Common mathematical calculations
•Global functions called as:

function_name(argument);
function_name(argument1, argument2, …);

cout << sqrt(400.0) << endl; // 20.0


double result;
result = pow(2.0, 3.0); // 2.0^3.0

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-5
What is a function?
User-defined functions
•We can define our own functions
•Here is a preview

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-6
What is a function?
User-defined functions
•Return zero if any of the arguments are negative

BEGINNING C++ PROGRAMMING FUNCTIONS


What is a function? S11-CPP-0040-7
Defining Functions
•name
•the name of the function
•same rules as for variables
•should be meaningful
•usually a verb or verb phrase
•parameter list
•the variables passed into the function
•their types must be specified
•return type
•the type of the data that is returned from the function
•body
•the statements that are executed when the function is called
•in curly braces {}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-1
Defining Functions
Example with no parameters

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-2
Defining Functions
Example with 1 parameter

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-3
Defining Functions
Example with no return type (void)

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-4
Defining Functions
Example with multiple parameters
void function_name(int a, std::string b)
{
statements(s);
return; // optional
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-5
Defining Functions
A function with no return type and no parameters
void say_hello () {
cout << "Hello" << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-6
Calling a function

void say_hello () {
cout << "Hello" << endl;
}

int main() {
say_hello();
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-7
Calling a function

void say_hello () {
cout << "Hello" << endl;
}

int main() {
for (int i{1} i<=10; ++i)
say_hello();
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-8
Calling a function

void say_world () {
cout << " World" << endl;
}

void say_hello () {
cout << "Hello" << endl;
say_world();
}

int main() {
say_hello();
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-9
Calling a function
void say_world () {
cout << " World" << endl;
cout << " Bye from say_world" << endl;
}

void say_hello () {
cout << "Hello" << endl;
say_world();
cout << " Bye from say_hello" << endl;
}

int main() {
say_hello();
cout << " Bye from main" << endl;
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-10
Calling functions
•Functions can call other functions
•Compiler must know the function details BEFORE it is called!
int main() {
say_hello(); // called BEFORE it is defined ERROR
return 0;
}

void say_hello ()
{
cout << "Hello" << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Definition S11-CPP-0060-11
Function Prototypes
• The compiler must ‘know’ about a function before it is used

• Define functions before calling them


• OK for small programs
• Not a practical solution for larger programs

• Use function prototypes


• Tells the compiler what it needs to know without a full function definition
• Also called forward declarations
• Placed at the beginning of the program
• Also used in our own header files (.h) – more about this later

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-1
Example
int function_name(); // prototype

int function_name()
{
statements(s);
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-2
Example
int function_name(int); // prototype
// or
int function_name(int a); // prototype

int function_name(int a) {
statements(s);
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-3
Example
void function_name(); // prototype

void function_name()
{
statements(s);
return; // optional
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-4
Example
void function_name(int a, std::string b);
// or
void function_name(int, std::string);

void function_name(int a, std::string b)


{
statements(s);
return; // optional
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-5
A function with no return type and no parameters
void say_hello();

void say_hello() {
cout << "Hello" << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-6
Calling a function
void say_hello();

int main() {
say_hello(); // OK
say_hello(100); // Error
cout << say_hello(); // Error
// No return value
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-7
Example
void say_hello(); // prototype void say_world () {
void say_world(); // prototype cout << " World" << endl;
cout << " Bye from say_world“ << endl;
int main() { }
say_hello();
cout << " Bye from main" << endl; void say_hello () {
return 0; cout << "Hello" << endl;
} say_world();
cout << " Bye from say_hello" << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Prototypes S11-CPP-0080-8
Function Parameters
• When we call a function we can pass in data to that function

• In the function call they are called arguments

• In the function definition they are called parameters

• They must match in number, order, and in type

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-1
Example
int add_numbers(int, int); // prototype

int main() {
int result {0};
result = add_numbers(100,200); // call
return 0;
}

int add_numbers(int a, int b) { // definition


return a + b;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-2
Example
void say_hello(std::string name) {
cout << "Hello " << name << endl;
}

say_hello("Frank");

std::string my_dog {"Buster"};


say_hello(my_dog);

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-3
Pass-by-value
• When you pass data into a function it is passed-by-value
• A copy of the data is passed to the function
• Whatever changes you make to the parameter in the function
does NOT affect the argument that was passed in.

• Formal vs. Actual parameters


• Formal parameters – the parameters defined in the function header
• Actual parameters – the parameter used in the function call, the arguments

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-4
Example
void param_test(int formal) { // formal is a copy of actual
cout << formal << endl; / 50
formal = 100; // only changes the local copy
cout << formal << endl; // 100
}

int main() {
int actual {50};
cout << actual << endl; // 50
param_test(actual); // pass in 50 to param_test
cout << actual << endl; // 50 - did not change
return 0
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-5
Function Return Statement
• If a function returns a value then it must use a return statement that returns a value

• If a function does not return a value (void) then the return statement is optional

• return statement can occur anywhere in the body of the function

• return statement immediately exits the function

• We can have multiple return statements in a function


• Avoid many return statements in a function

• The return value is the result of the function call

BEGINNING C++ PROGRAMMING FUNCTIONS


Function Parameters S11-CPP-0100-6
Default Argument Values
•When a function is called, all arguments must be supplied

•Sometimes some of the arguments have the same values most of the time

•We can tell the compiler to use default values if the arguments are not supplied

•Default values can be in the prototype or definition, not both


•best practice – in the prototype
•must appear at the tail end of the parameter list

•Can have multiple default values


•must appear consecutively at the tail end of the parameter list

BEGINNING C++ PROGRAMMING FUNCTIONS


Default Argument Values S11-CPP-0120-1
Default Argument Values
Example – no default arguments
double calc_cost(double base_cost, double tax_rate);

double calc_cost(double base_cost, double tax_rate) {


return base_cost += (base_cost * tax_rate);
}

int main() {
double cost {0};
cost = calc_cost(100.0, 0.06);
return 0;
}
BEGINNING C++ PROGRAMMING FUNCTIONS
Default Argument Values S11-CPP-0120-2
Default Argument Values
Example – single default argument
double calc_cost(double base_cost, double tax_rate = 0.06);

double calc_cost(double base_cost, double tax_rate) {


return base_cost += (base_cost * tax_rate);
}

int main() {
double cost {0};
cost = calc_cost(200.0); // will use the default tax
cost = calc_cost (100.0, 0.08); // will use 0.08 not the defauly
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Default Argument Values S11-CPP-0120-3
Default Argument Values
Example – multiple default arguments
double calc_cost(double base_cost, double tax_rate = 0.06, double shipping = 3.50);

double calc_cost(double base_cost, double tax_rate, double shipping) {


return base_cost += (base_cost * tax_rate) + shipping;
}

int main() {
double cost {0};
cost = calc_cost (100.0, 0.08, 4.25); // will use no defaults
cost = calc_cost(100.0, 0.08); // will use default shipping
cost = calc_cost(200.0); // will use default tax and shipping
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Default Argument Values S11-CPP-0120-4
Overloading Functions
•We can have functions that have different parameter lists that have the
same name

•Abstraction mechanism since we can just think ‘print’ for example

•A type of polymorphism
•We can have the same name work with different data types to execute similar
behavior

•The compiler must be able to tell the functions apart based on the
parameter lists and argument supplied

BEGINNING C++ PROGRAMMING FUNCTIONS


Overloading Functions S11-CPP-0140-1
Overloading Functions
Example
int add_numbers(int, int); // add ints
double add_numbers(double, double); // add doubles

int main() {
cout << add_numbers(10,20) << endl; // integer
cout << add_numbers(10.0, 20.0) << endl; // double
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Overloading Functions S11-CPP-0140-2
Overloading Functions
Example
int add_numbers(int a, int b) {
return a + b;
}

double add_numbers(double a, double b) {


return a + b;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Overloading Functions S11-CPP-0140-3
Overloading Functions
Example
void display(int n);
void display(double d);
void display(std::string s);
void display(std::string s, std::string t);
void display(std::vector<int> v);
void display(std::vector<std::string> v);

BEGINNING C++ PROGRAMMING FUNCTIONS


Overloading Functions S11-CPP-0140-4
Overloading Functions
Return type is not considered
int get_value();
double get_value();

// Error

cout << get_value() << endl; // which one?

BEGINNING C++ PROGRAMMING FUNCTIONS


Overloading Functions S11-CPP-0140-5
Passing Arrays To Functions
• We can pass an array to a function by providing square brackets in the formal
parameter description

void print_array(int numbers []);

• The array elements are NOT copied

• Since the array name evaluates to the location of the array in memory – this address is
what is copied

• So the function has no idea how many elements are in the array since all it knows is the
location of the first element (the name of the array)

BEGINNING C++ PROGRAMMING FUNCTIONS


Passing Arrays To Functions S11-CPP-0160-1
Example
void print_array(int numbers []);

int main() {
int my_numbers[] {1,2,3,4,5};
print_array(my_numbers);
return 0;
}

void print_array(int numbers []) {


// Doesn’t know how many elements are in the array???
// we need to pass in the size!!
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Passing Arrays To Functions S11-CPP-0160-2
Example
void print_array(int numbers [], size_t size);

int main() {
int my_numbers[] {1,2,3,4,5};
print_array(my_numbers, 5); / 1 2 3 4 5
return 0;
}

void print_array(int numbers [], size_t size) {


for (size_t i{0}; i < size; ++i )
cout << numbers[i] << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Passing Arrays To Functions S11-CPP-0160-3
Example
• Since we are passing the location of the array
• The function can modify the actual array!

void zero_array(int numbers [], size_t size) {


for (size_t i{0}; i < size; ++i )
numbers[i] = 0; // zero out array element
}
int main() {
int my_numbers[] {1,2,3,4,5};
zero_array(my_numbers, 5); // my_numbers is now zeroes!
print_array(my_numbers, 5); // 0 0 0 0 0
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Passing Arrays To Functions S11-CPP-0160-4
const parameters
• We can tell the compiler that function parameters are const (read-only)
• This could be useful in the print_array function since it should NOT modify the
array
void print_array(const int numbers [], size_t size) {
for (size_t i{0}; i < size; ++i )
cout << numbers[i] << endl;
numbers[i] = 0; // any attempt to modify the array
// will result in a compiler error
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Passing Arrays To Functions S11-CPP-0160-5
Pass by Reference
• Sometimes we want to be able to change the actual parameter from within
the function body

• In order to achieve this we need the location or address of the actual


parameter

• We saw how this is the effect with array, but what about other variable types?

• We can use reference parameters to tell the compiler to pass in a reference to


the actual parameter.

• The formal parameter will now be an alias for the actual parameter

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-1
Example
void scale_number(int &num); // prototype

int main() {
int number {1000};
scale_number(number); // call
cout << number << endl; // 100
return 0;
}

void scale_number(int &num) { // definition


if (num > 100)
num = 100;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-2
Example
void swap(int &a, int &b);

int main() {
int x{10}, y{20};
cout << x << " " << y << endl; // 10 20
swap(x, y);
cout << x << " " << y << endl; // 20 10
return 0;
}

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-3
vector example – pass by value
void print(std::vector<int> v);

int main() {
std::vector<int> data {1,2,3,4,5};
print(data); // 1 2 3 4 5
return 0;
}

void print(std::vector<int> v) {
for (auto num: v)
cout << num << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-4
vector example – pass by reference
void print(std::vector<int> &v);

int main() {
std::vector<int> data {1,2,3,4,5};
print(data); // 1 2 3 4 5
return 0;
}

void print(std::vector<int> &v) {


for (auto num: v)
cout << num << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-5
vector example – pass by const reference
void print(const std::vector<int> &v);

int main() {
std::vector<int> data {1,2,3,4,5};
print(data); // 1 2 3 4 5
return 0;
}

void print(const std::vector<int> &v) {


v.at(0) = 200; // ERROR
for (auto num: v)
cout << num << endl;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Pass by Reference S11-CPP-0180-6
Scope Rules
• C++ uses scope rules to determine where an identifier can be used

• C++ uses static or lexical scoping

• Local or Block scope

• Global scope

BEGINNING C++ PROGRAMMING FUNCTIONS


Scope Rules S11-CPP-0190-1
Local or Block scope
• Identifiers declared in a block { }

• Function parameters have block scope

• Only visible within the block { } where declared

• Function local variables are only active while the function is executing

• Local variables are NOT preserved between function calls

• With nested blocks inner blocks can ‘see’ but outer blocks cannot ‘see’ in

BEGINNING C++ PROGRAMMING FUNCTIONS


Scope Rules S11-CPP-0190-2
Static local variables
• Declared with static qualifier

static int value {10};

• Value IS preserved between function calls

• Only initialized the first time the function is called

BEGINNING C++ PROGRAMMING FUNCTIONS


Scope Rules S11-CPP-0190-3
Global scope
• Identifier declared outside any function or class

• Visible to all parts of the program after the global identifier has been declared

• Global constants are OK

• Best practice – don’t use global variables

BEGINNING C++ PROGRAMMING FUNCTIONS


Scope Rules S11-CPP-0190-4
How do Function Calls Work?
• Functions use the ‘function call stack’
• Analogous to a stack of books
• LIFO – Last In First Out
• push and pop

• Stack Frame or Activation Record


• Functions must return control to function that called it
• Each time a function is called we create an new activation record and push it on
stack
• When a function terminates we pop the activation record and return
• Local variables and function parameters are allocated on the stack

• Stack size is finite – Stack Overflow

BEGINNING C++ PROGRAMMING FUNCTIONS


How do Function Calls Work? S11-CPP-0200-1
Inline Functions
• Function calls have a certain amount of overhead

• You saw what happens on the call stack

• Sometimes we have simple functions

• We can suggest to the compiler to compile them ‘inline’


• avoid function call overhead
• generate inline assembly code
• faster
• could cause code bloat

• Compilers optimizations are very sophisticated


• will likely inline even without your suggestion

BEGINNING C++ PROGRAMMING FUNCTIONS


Inline Functions S11-CPP-0220-1
Example
inline int add_numbers(int a, int b) { // definition
return a + b;
}

int main() {
int result {0};
result = add_numbers(100,200); // call
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Inline Functions S11-CPP-0220-2
Recursive Functions
• A recursive function is a function that calls itself
• Either directly or indirectly through another function

• Recursive problem solving


• Base case
• Divide the rest of problem into subproblem and do recursive call

• There are many problems that lend themselves to recursive solutions

• Mathematic – factorial, Fibonacci, fractals,…

• Searching and sorting – binary search, search trees, …

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-1
Example - Factorial

• Base case:
• factorial(0) = 1

• Recursive case:
• factorial(n) = n * factorial(n-1)

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-2
Example - Factorial
unsigned long long factorial(unsigned long long n) {
if (n == 0)
return 1; // base case
return n * factorial(n-1); // recursive case
}
int main() {
cout << factorial(8) << endl; // 40320
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-3
Example - Fibonacci

• Base case:
• Fib(0) = 0
• Fib(1) = 1

• Recursive case:
• Fib(n) = Fib(n-1) + Fib(n-2)

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-4
Example - Factorial
unsigned long long fibonacci(unsigned long long n) {
if (n <= 1)
return n; // base cases
return fibonacci(n-1) + fibonacci(n-2); // recursion
}
int main() {
cout << fibonacci(30) << endl; // 832040
return 0;
}

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-5
Important notes
• If recursion doesn’t eventually stop you will have infinite recursion

• Recursion can be resource intensive

• Remember the base case(s)


• It terminates the recursion

• Only use recursive solutions when it makes sense

• Anything that can be done recursively can be done iteratively


• Stack overflow error

BEGINNING C++ PROGRAMMING FUNCTIONS


Recursive Functions S11-CPP-0240-6
Overview
• What is a pointer? • What is a reference?
• Declaring pointers • Review passing references to functions
• Storing addresses in pointers • const and references
• Dereferencing pointers • Reference variables in range-based for loops
• Dynamic memory allocation • Potential reference pitfalls
• Pointer arithmetic
• Pointers and arrays • Raw vs. Smart pointers
• Pass-by-reference with pointers
• const and pointers
• Using pointers to functions
• Potential pointer pitfalls

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


SectionOverview S12-CPP-0020-1
What is a Pointer?
• A variable
• whose value is an address

• What can be at that address?


• Another variable
• A function

• Pointers point to variables or functions?

• If x is an integer variable and its value is 10


then I can declare a pointer that points to it

• To use the data that the pointer is pointing to you must know its type

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Pointer? S12-CPP-0040-1
Why use Pointers?
Can’t I just use the variable or function itself?
Yes, but not always

• Inside functions, pointers can be used to access data that are defined outside the function.
Those variables may not be in scope so you can’t access them by their name

• Pointers can be used to operate on arrays very efficiently

• We can allocate memory dynamically on the heap or free store.


• This memory doesn’t even have a variable name.
• The only way to get to it is via a pointer

• With OO. pointers are how polymorphism works!

• Can access specific addresses in memory


• useful in embedded and systems applications

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Pointer? S12-CPP-0040-2
Declaring Pointers

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Declaring Pointers S12-CPP-0060-1
Declaring Pointers
Initializing pointer variables to ‘point nowhere’

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Declaring Pointers S12-CPP-0060-2
Declaring Pointers
Initializing pointer variables to ‘point nowhere’

• Always initialize pointers

• Uninitialized pointers contain garbage data and can ‘point anywhere’

• Initializing to zero or nullptr (C++ 11) represents address zero

• implies that the pointer is ‘pointing nowhere’

• If you don’t initialize a pointer to point to a variable or function then you should initialize
it to nullptr to ‘make it null’

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Declaring Pointers S12-CPP-0060-3
Accessing Pointer Address?
& the address operator
•Variables are stored in unique addresses
•Unary operator
•Evaluates to the address of its operand
•Operand cannot be a constant or expression that evaluates to temp values

int num{10};

cout << "Value of num is: " << num << endl; // 10

cout << "sizeof of num is: " << sizeof num << endl; // 4

cout << "Address of num is: " << &num << endl; // 0x61ff1c

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Accessing And Storing Pointer Addresses S12-CPP-0080-1
Accessing Pointer Address?
& the address operator - example

int *p;

cout << "Value of p is: " << p << endl; // 0x61ff60 - garbage

cout << "Address of p is: " << &p << endl; // 0x61ff18

cout << "sizeof of p is: " << sizeof p << endl; // 4

p = nullptr;// set p to point nowhere

cout << "Value of p is: " << p << endl; // 0

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Accessing And Storing Pointer Addresses S12-CPP-0080-2
Accessing Pointer Addresses?
sizeof a pointer variable

•Don’t confuse the size of a pointer and the size of what it points to
•All pointers in a program have the same size
•They may be pointing to very large or very small types
int *p1 {nullptr};
double *p2 {nullptr};
unsigned long long *p3 {nullptr};
vector<string> *p4 {nullptr};
string *p5 {nullptr};

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Accessing And Storing Pointer Addresses S12-CPP-0080-3
Storing an Address in Pointer Variable?
Typed pointers

•The compiler will make sure that the address stored in a


pointer variable is of the correct type
int score {10};
double high_temp {100.7};

int *score_ptr {nullptr};

score_ptr = &score; // OK

score_ptr = &high_temp; // Compiler Error

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Accessing And Storing Pointer Addresses S12-CPP-0080-4
Storing an Address in Pointer Variable?
& the address operator
•Pointers are variables so they can change
•Pointers can be null
•Pointers can be uninitialized

double high_temp {100.7};


double low_temp {37.2};

double *temp_ptr;

temp_ptr = &high_temp; // points to high_temp


temp_ptr = &low_temp; // now points to low_temp

temp_ptr = nullptr;

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Accessing And Storing Pointer Addresses S12-CPP-0080-5
Dereferencing a Pointer
Access the data we’re pointing to – dereferencing a pointer
•If score_ptr is a pointer and has a valid address
•Then you can access the data at the address contained in the score_ptr
using the dereferencing operator *

int score {100};


int *score_ptr {&score};

cout << *score_ptr << endl; // 100

*score_ptr = 200;
cout << *score_ptr << endl; // 200
cout << score << endl; // 200

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dereferencing a Pointer S12-CPP-0100-1
Dereferencing a Pointer
Access the data we’re pointing to
double high_temp {100.7};
double low_temp {37.4};
double *temp_ptr {&high_temp};

cout << *temp_ptr << endl; // 100.7

temp_ptr = &low_temp;

cout << *temp_ptr << endl; // 37.4

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dereferencing a Pointer S12-CPP-0100-2
Dereferencing a Pointer
Access the data we’re pointing to

string name {"Frank"};

string *string_ptr {&name};

cout << *string_ptr << endl; // Frank

name = "James";

cout << *string_ptr << endl; // James

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dereferencing a Pointer S12-CPP-0100-3
Dynamic Memory Allocation
Allocating storage from the heap at runtime

• We often don’t know how much storage we need until we need it

• We can allocate storage for a variable at run time

• Recall C++ arrays


• We had to explicitly provide the size and it was fixed
• But vectors grow and shrink dynamically

• We can use pointers to access newly allocated heap storage

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dynamic Memory Allocation S12-CPP-0120-1
Dynamic Memory Allocation
using new to allocate storage

int *int_ptr {nullptr};

int_ptr = new int; // allocate an integer on the heap

cout << int_ptr << endl; // 0x2747f28

cout << *int_ptr << endl; // 41188048 - garbage

*int_ptr = 100;

cout << *int_ptr << endl; // 100

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dynamic Memory Allocation S12-CPP-0120-2
Dynamic Memory Allocation
using delete to deallocate storage

int *int_ptr {nullptr};

int_ptr = new int; // allocate an integer on the heap

. . .

delete int_ptr; // frees the allocated storage

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dynamic Memory Allocation S12-CPP-0120-3
Dynamic Memory Allocation
using new[] to allocate storage for an array

int *array_ptr {nullptr};


int size {};

cout << "How big do you want the array? ";


cin >> size;

array_ptr = new int[size]; // allocate array on the heap

// We can access the array here


// we’ll see how in a few slides

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dynamic Memory Allocation S12-CPP-0120-4
Dynamic Memory Allocation
using delete[] to deallocate storage for an array

int *array_ptr {nullptr};


int size {};

cout << “How big do you want the array?”;


cin >> size;

array_ptr = new int[size]; // allocate array on the heap

. . .

delete [] array_ptr; // free allocated storage

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Dynamic Memory Allocation S12-CPP-0120-5
Relationship Between Arrays and Pointers
• The value of an array name is the address of the first element in the array

• The value of a pointer variable is an address

• If the pointer points to the same data type as the array element then the
pointer and array name can be used interchangeably (almost)

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-1
Relationship Between Arrays and Pointers
int scores[] {100, 95, 89};

cout << scores << endl; // 0x61fec8


cout << *scores << endl; // 100

int *score_ptr {scores};

cout << score_ptr << endl; // 0x61fec8

cout << *score_ptr << endl; // 100

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-2
Relationship Between Arrays and Pointers
int scores[] {100, 95, 89};

int *score_ptr {scores};

cout << score_ptr[0] << endl; // 100

cout << score_ptr[1] << endl; // 95

cout << score_ptr[2] << endl; // 89

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-3
Using pointers in expressions
int scores[] {100, 95, 89};

int *score_ptr {scores};

cout << score_ptr << endl; // 0x61ff10

cout << (score_ptr + 1) << endl; // 0x61ff14

cout << (score_ptr + 2) << endl; // 0x61ff18

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-4
Using pointers in expressions
int scores[] {100, 95, 89};

int *score_ptr {scores};

cout << *score_ptr << endl; // 100

cout << *(score_ptr + 1) << endl; // 95

cout << *(score_ptr + 2) << endl; // 89

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-5
Subscript and Offset notation equivalence

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Arrays and Pointers S12-CPP-0130-6
Pointer Arithmetic
• Pointers can be used in
• Assignment expressions
• Arithmetic expressions
• Comparison expressions

• C++ allows pointer arithmetic

• Pointer arithmetic only makes sense with raw arrays

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-1
++ and --

• (++) increments a pointer to point to the next array element

int_ptr++;

• (--) decrements a pointer to point to the previous array element

int_ptr--;

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-2
+ and -
• (+) increment pointer by n * sizeof(type)

int_ptr += n; or int_ptr = int_ptr + n;

• (-) decrement pointer by n * sizeof(type)

int_ptr -= n; or int_ptr = int_ptr - n;

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-3
Subtracting two pointers
• Determine the number of elements between the pointers

• Both pointers must point to the same data type

int n = int_ptr2 – int_ptr1;

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-4
Comparing two pointers == and !=
Determine if two pointers point to the same location
• does NOT compare the data where they point!

string s1 {"Frank"};
string s2 {"Frank"};

string *p1 {&s1};


string *p2 {&s2};
string *p3 {&s1};

cout << (p1 == p2) << endl; // false


cout << (p1 == p3) << endl; // true

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-5
Comparing the data pointers point to
Determine if two pointers point to the same data
• you must compare the referenced pointers

string s1 {"Frank"};
string s2 {"Frank"};

string *p1 {&s1};


string *p2 {&s2};
string *p3 {&s1};

cout << (*p1 == *p2) << endl; // true


cout << (*p1 == *p3) << endl; // true

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Pointer Arithmetic S12-CPP-0140-6
Passing pointers to a function
const and Pointers

• There are several ways to qualify pointers


using const

• Pointers to constants

• Constant pointers

• Constant pointers to constants

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


const and Pointers S12-CPP-0160-1
Pointers to constants
• The data pointed to by the pointers is constant and cannot be changed.

• The pointer itself can change and point somewhere else.

int high_score {100};


int low_score { 65};
const int *score_ptr { &high_score };

*score_ptr = 86; // ERROR


score_ptr = &low_score; // OK

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


const and Pointers S12-CPP-0160-2
Constant pointers
• The data pointed to by the pointers can be changed.

• The pointer itself cannot change and point somewhere else

int high_score {100};


int low_score { 65};
int *const score_ptr { &high_score };

*score_ptr = 86; // OK
score_ptr = &low_score; // ERROR

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


const and Pointers S12-CPP-0160-3
Constant pointers to constants
• The data pointed to by the pointer is constant and cannot be changed.

• The pointer itself cannot change and point somewhere else.

int high_score {100};


int low_score { 65};
const int *const score_ptr { &high_score };

*score_ptr = 86; // ERROR


score_ptr = &low_score; // ERROR

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


const and Pointers S12-CPP-0160-4
Passing pointers to a function
• Pass-by-reference with pointer parameters

• We can use pointers and the dereference operator to achieve


pass-by-reference

• The function parameter is a pointer

• The actual parameter can be a pointer or address of a variable

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Passing Pointers to Functions S12-CPP-0180-1
Passing pointers to a function
Pass-by-reference with pointers – defining the function

void double_data(int *int_ptr);

void double_data(int *int_ptr) {


*int_ptr *= 2;

// *int_ptr = *int_ptr * 2;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Passing Pointers to Functions S12-CPP-0180-2
Passing pointers to a function
Pass-by-reference with pointers – calling the function

int main() {
int value {10};

cout << value << endl; // 10

double_data( &value);

cout << value << endl; // 20


}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Passing Pointers to Functions S12-CPP-0180-3
Returning a Pointer from a Function
• Functions can also return pointers

type *function();

• Should return pointers to


• Memory dynamically allocated in the function
• To data that was passed in

• Never return a pointer to a local function variable!

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-1
returning a parameter

int *largest_int(int *int_ptr1, int *int_ptr2) {


if (*int_ptr1 > *int_ptr2)
return int_ptr1;
else
return int_ptr2;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-2
returning a parameter
int main() {
int a{100};
int b{200};

int *largest_ptr {nullptr};


largest_ptr = largest_int(&a, &b);
cout << *largest_ptr << endl; // 200
return 0;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-3
returning dynamically allocated memory
int *create_array(size_t size, int init_value = 0) {

int *new_storage {nullptr};

new_storage = new int[size];


for (size_t i{0}; i < size; ++i)
*(new_storage + i) = init_value;
return new_storage;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-4
returning dynamically allocated memory
int main() {
int *my_array; // will be allocated by the function

my_array = create_array(100,20); // create the array

// use it

delete [] my_array; / / be sure to free the storage


return 0;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-5
Never return a pointer to a local variable!!

int *dont_do_this () {
int size {};
. . .
return &size;
}
int *or_this () {
int size {};
int *int_ptr {&size};
. . .
return int_ptr;
}

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Returning a Pointer S12-CPP-0200-6
Potential Pointer Pitfalls
• Uninitialized pointers

• Dangling Pointers

• Not checking if new failed to allocate memory

• Leaking memory

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Potential Pointer Pitfalls S12-CPP-0220-1
Uninitialized pointers

int *int_ptr; // pointing anywhere

. . .

*int_ptr = 100; // Hopefully a crash

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Potential Pointer Pitfalls S12-CPP-0220-2
Dangling pointer
• Pointer that is pointing to released memory
• For example, 2 pointers point to the same data
• 1 pointer releases the data with delete
• The other pointer accesses the release data

• Pointer that points to memory that is invalid


• We saw this when we returned a pointer to a function local variable

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Potential Pointer Pitfalls S12-CPP-0220-3
Not checking if new failed

• If new fails an exception is thrown

• We can use exception handling to catch exceptions

• Dereferencing a null pointer will cause your program to crash

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Potential Pointer Pitfalls S12-CPP-0220-4
Leaking memory

• Forgetting to release allocated memory with delete

• If you lose your pointer to the storage allocated on the heap you have not way
to get to that storage again

• The memory is orphaned or leaked

• One of the most common pointer problems

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Potential Pointer Pitfalls S12-CPP-0220-5
What is a Reference?
•An alias for a variable

•Must be initialized to a variable when declared

•Cannot be null

•Once initialized cannot be made to refer to a different variable

•Very useful as function parameters

•Might be helpful to think of a reference as a constant pointer that is


automatically dereferenced

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-1
What is a reference?
Using references in range-based for loop
vector<string> stooges {"Larry", "Moe", "Curly"};

for (auto str: stooges)


str = "Funny"; // changes the copy

for (auto str:stooges)


cout << str << endl; // Larry, Moe, Curly

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-2
What is a reference?
Using references in range-based for loop
vector<string> stooges {"Larry", "Moe", "Curly"};

for (auto &str: stooges)


str = "Funny"; // changes the actual

for (auto str:stooges)


cout << str << endl; // Funny, Funny, Funny

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-3
What is a reference?
Using references in range-based for loop
vector<string> stooges {"Larry", "Moe", "Curly"};

for (auto const &str: stooges)


str = "Funny"; // compiler error

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-4
What is a reference?
Using references in range-based for loop
vector<string> stooges {"Larry", "Moe", "Curly"};

for (auto const &str:stooges)


cout << str << endl; // Larry, Moe, Curly

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-5
What is a reference?
Passing references to functions

•Please refer to the section 11 videos and examples

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


What is a Reference S12-CPP-0240-6
l-values
• l-values
• values that have names and are addressable
• modifiable if they are not constants

int x {100}; // x is an l-value


x = 1000;
x = 1000 + 20;

string name; // name is an l-value


name = "Frank";

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-1
l-values
• l-values
• values that have names and are addressable
• modifiable if they are not constants

100 = x; // 100 is NOT an l-value


(1000 + 20) = x; // (1000 + 20) is NOT an l-value

string name;
name = "Frank";
"Frank" = name; // "Frank" is NOT an l-value

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-2
r-values
• r-value (non-addressable and non-assignable)
• A value that’s not an l-value
▪ on the right-hand side of an assignment expression
▪ a literal
▪ a temporary which is intended to be non-modifiable

int x {100}; // 100 is an r-value


int y = x + 200; // (x+200)is an r-value

string name;
name = "Frank"; // "Frank" is an r-value

int max_num = max(20,30); // max(20,30) is an r-value

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-3
r-values
• r-values can be assigned to l-values explicitly

int x {100};
int y {0};

y = 100; // r-value 100 assigned to l-value y

x = x + y; // r-value (x+y) assigned to l-value x

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-4
l-value references
• The references we’ve used are l-value references
• Because we are referencing l-values

int x {100};

int &ref1 = x; // ref1 is reference to l-value


ref1 = 1000;

int &ref2 = 100; // Error 100 is an r-value

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-5
l-value references
• The same when we pass-by-reference

int square(int &n) {


return n*n;
}

int num {10};

square(num); // OK

square(5); // Error – can’t reference r-value 5

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Land R-Values S12-CPP-0250-6
When to use pointers vs. references parameters
• Pass-by-value
• when the function does not modify the actual parameter, and
• the parameter is small and efficient to copy like simple types (int, char,
double, etc.)

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-1
When to use pointers vs. references parameters
• Pass-by-reference using a pointer
• when the function does modify the actual parameter,
and
• the parameter is expensive to copy,
and
• Its OK to the pointer is allowed a nullptr value

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-2
When to use pointers vs. references parameters
• Pass-by-reference using a pointer to const
• when the function does not modify the actual parameter,
and
• the parameter is expensive to copy,
and
• Its OK to the pointer is allowed a nullptr value

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-3
When to use pointers vs. references parameters
• Pass-by-reference using a const pointer to const
• when the function does not modify the actual parameter,
and
• the parameter is expensive to copy,
and
• Its OK to the pointer is allowed a nullptr value,
and
• You don’t want to modify the pointer itself

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-4
When to use pointers vs. references parameters
• Pass-by-reference using a reference
• when the function does modify the actual parameter,
and
• the parameter is expensive to copy,
and
• The parameter will never be nullptr

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-5
When to use pointers vs. references parameters
• Pass-by-reference using a const reference
• when the function does not modify the actual parameter,
and
• the parameter is expensive to copy,
and
• The parameter will never be nullptr

BEGINNING C++ PROGRAMMING POINTERS AND REFERENCES


Section Recap S12-CPP-0280-6
Object-Oriented Programming – Classes and Objects
• What is Object-Oriented Programming?
• What are Classes and Objects?
• Declaring Classes and creating Objects
• Dot and pointer operators
• public and private access modifiers
• Methods, Constructors and Destructors
• class methods
• default and overloaded constructors
• copy and move constructors
• shallow vs. deep copying
• this pointer

• static class members


• struct vs. class
• friend of a class

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Section Overview S13-CPP-0020-1
What is Object-Oriented Programming?
• Procedural Programming

• Procedural Programming limitations

• OO Programming concepts and their advantages

• OO Programming limitations

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-1
Procedural programming
• Focus is on processes or actions that a program takes

• Programs are typically a collection of functions

• Data is declared separately

• Data is passed as arguments into functions

• Fairly easy to learn

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-2
Procedural programming - Limitations
• Functions need to know the structure of the data.
• if the structure of the data changes many functions must be changed

• As programs get larger they become more:


• difficult to understand
• difficult to maintain
• difficult to extend
• difficult to debug
• difficult to reuse code
• fragile and easier to break

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-3
What is Object-Oriented Programming?
• Classes and Objects
• focus is on classes that model real-world domain entities
• allows developers to think at a higher level of abstraction
• used successfully in very large programs

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-4
What is Object-Oriented Programming?
• Encapsulation
• objects contain data AND operations that work on that data
• Abstract Data Type (ADT)

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-5
What is Object-Oriented Programming?
• Information-hiding
• implementation-specific logic can be hidden
• users of the class code to the interface since they don’t need to know the
implementation
• more abstraction
• easier to test, debug, maintain and extend

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-6
What is Object-Oriented Programming?
• Reusability
• easier to reuse classes in other applications
• faster development
• higher quality

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-7
What is Object-Oriented Programming?

• Inheritance
• can create new classes in term of existing classes
• reusability
• polymorphic classes

• Polymorphism and more…

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-8
Limitations
• Not a panacea
• OO Programming won’t make bad code better
• not suitable for all types of problems
• not everything decomposes to a class

• Learning curve
• usually a steeper leaning curve, especially for C++
• many OO languages, many variations of OO concepts

• Design
• usually more up-front design is necessary to create good models and hierarchies

• Programs can be:


• larger in size
• slower
• more complex

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


What Is OOProgramming? S13-CPP-0040-9
Classes and Objects
• Classes
• blueprint from which objects are created
• a user-defined data-type
• has attributes (data)
• has methods (functions)
• can hide data and methods
• provides a public interface

• Example classes
• Account
• Employee
• Image
• std::vector
• std::string

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Classes and Objects S13-CPP-0060-1
Classes and Objects
• Objects
• created from a class
• represents a specific instance of a class
• can create many, many objects
• each has its own identity
• each can use the defined class methods

• Example Account objects


• Frank’s account is an instance of an Account
• Jim’s account is an instance of an Account
• Each has its own balance, can make deposits, withdrawals, etc.

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Classes and Objects S13-CPP-0060-2
Classes and Objects
int high_score;
int low_score;

Account frank_account;
Account jim_account;

std::vector<int> scores;
std::string name;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Classes and Objects S13-CPP-0060-3
Declaring a Class

class Class_Name
{

// declaration(s);

};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-1
Player
class Player
{
// attributes
std::string name;
int health;
int xp;

// methods
void talk(std::string text_to_say);
bool is_dead();
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-2
Creating objects
Player frank;
Player hero;

Player *enemy = new Player();


delete enemy;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-3
Account

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-4
Creating objects
Account frank_account;
Account jim_account;

Account *mary_account = new Account();


delete mary_account;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-5
Creating objects
Account frank_account;
Account jim_account;

Account accounts[] {frank_account, jim_account};

std::vector<Account> accounts1 {frank_account};


accounts1.push_back(jim_account);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Declaring Classes And Objects S13-CPP-0080-6
Accessing Class Members
• We can access
• class attributes
• class methods

• Some class members will not be accessible (more on that later)

• We need an object to access instance variables

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Accessing Class Members S13-CPP-0100-1
Accessing Class Members
If we have an object (dot operator)

• Using the dot operator

Account frank_account;

frank_account.balance;
frank_account.deposit(1000.00);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Accessing Class Members S13-CPP-0100-2
Accessing Class Members
If we have a pointer to an object (member of pointer operator)
• Dereference the pointer then use the dot operator.

Account *frank_account = new Account();

(*frank_account).balance;
(*frank_account).deposit(1000.00);
• Or use the member of pointer operator (arrow operator)

Account *frank_account = new Account();

frank_account->balance;
frank_account->deposit(1000.00);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Accessing Class Members S13-CPP-0100-3
Class Member Access Modifiers
public, private, and protected
•public
•accessible everywhere

•private
•accessible only by members or friends of the class

•protected
•used with inheritance – we’ll talk about it in the next section

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-1
Class Member Access Modifiers
public

class Class_Name
{
public:

// declaration(s);

};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-2
Class Member Access Modifiers
private

class Class_Name
{
private:

// declaration(s);

};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-3
Class Member Access Modifiers
protected

class Class_Name
{
protected:

// declaration(s);

};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-4
Declaring a Class
Player

class Player
{
private:
std::string name;
int health;
int xp;
public:
void talk(std::string text_to_say);
bool is_dead();
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-5
Creating objects

Player frank;
frank.name = "Frank"; // Compiler error
frank.health = 1000; // Compiler error
frank.talk("Ready to battle"); // OK

Player *enemy = new Player();


enemy->xp = 100; // Compiler error
enemy->talk("I will hunt you down"); // OK

delete enemy;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-6
Declaring a Class
Account

class Account
{
private:
std::string name;
double balance;

public:
bool withdraw(double amount);
bool deposit(double amount);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-7
Creating objects

Account frank_account;
frank_account.balance = 10000000.00; // Compiler error
frank_account.deposit(10000000.0); // OK
frank_account.name = "Frank’s Account"; // Compiler error

Account *mary_account = new Account();

mary_account->balance = 10000.0; // Compiler error


mary_account->withdraw(10000.0); // OK

delete mary_account;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Public and Private S13-CPP-0120-8
Implementing Member Methods
•Very similar to how we implemented functions

•Member methods have access to member attributes


• So you don’t need to pass them as arguments!

•Can be implemented inside the class declaration


• Implicitly inline

•Can be implemented outside the class declaration


• Need to use Class_name::method_name

•Can separate specification from implementation


• .h file for the class declaration
• .cpp file for the class implementation

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-1
Implementing Member Methods
Inside the class declaration
class Account {

private:
double balance;
public:
void set_balance(double bal) {
balance = bal;
}
double get_balance() {
return balance;
}
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-2
Implementing Member Methods
Outside the class declaration
class Account {

private:
double balance;
public:
void set_balance(double bal);
double get_balance();
};

void Account::set_balance(double bal) {


balance = bal;
}
double Account::get_balance() {
return balance;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-3
Separating Specification from Implementation
Account.h
class Account {

private:
double balance;
public:
void set_balance(double bal);
double get_balance();
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-4
Separating Specification from Implementation
Include Guards
#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_

// Account class declaration

#endif

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-5
Separating Specification from Implementation
Account.h
#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_

class Account {

private:
double balance;
public:
void set_balance(double bal);
double get_balance();
};

#endif

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-6
Separating Specification from Implementation
Account.h - #pragma once
#pragma once

class Account {

private:
double balance;
public:
void set_balance(double bal);
double get_balance();
};
BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS
Implementing Member Methods S13-CPP-0140-7
Separating Specification from Implementation
Account.cpp
#include "Account.h"

void Account::set_balance(double bal) {


balance = bal;
}

double Account::get_balance() {
return balance;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Implementing Member Methods S13-CPP-0140-8
Separating Specification from Implementation
main.cpp
#include <iostream>
#include "Account.h"

int main() {
Account frank_account;
frank_account.set_balance(1000.00);
double bal = frank_account.get_balance();

std::cout << bal << std::endl; // 1000


return 0;
}
BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS
Implementing Member Methods S13-CPP-0140-9
Constructors
• Special member method

• Invoked during object creation

• Useful for initialization

• Same name as the class

• No return type is specified

• Can be overloaded

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-1
Player Constructors
class Player
{
private:
std::string name;
int health;
int xp;
public:
// Overloaded Constructors
Player();
Player(std::string name);
Player(std::string name, int health, int xp);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-2
Account Constructors
class Account
{
private:
std::string name;
double balance;
public:
// Constructors
Account();
Account(std::string name, double balance);
Account(std::string name);
Account(double balance);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-3
Destructors
• Special member method

• Same name as the class proceeded with a tilde (~)

• Invoked automatically when an object is destroyed

• No return type and no parameters

• Only 1 destructor is allowed per class – cannot be overloaded!

• Useful to release memory and other resources

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-4
Player Destructor
class Player
{
private:
std::string name;
int health;
int xp;
public:
Player();
Player(std::string name);
Player(std::string name, int health, int xp);
// Destructor
~Player();
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-5
Account Destructor
class Account
{
private:
std::string name;
double balance;
public:
Account();
Account(std::string name, double balance);
Account(std::string name);
Account(double balance);
// Destructor
~Account();
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-6
Creating objects
{
Player slayer;
Player frank {"Frank", 100, 4 };
Player hero {"Hero"};
Player villain {"Villain"};
// use the objects
} // 4 destructors called

Player *enemy = new Player("Enemy", 1000, 0);


delete enemy; // destructor called

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Constructors and Destructors S13-CPP-0160-7
The Default Constructor
• Does not expect any arguments
• Also called the no-args constructor

• If your write no constructors at all for a class


• C++ will generate a Default Constructor that does nothing

• Called when you instantiate a new object with no arguments

Player frank;
Player *enemy = new Player;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-1
Declaring a Class
Account – using default constructor
class Account
{
private:
std::string name;
double balance;
public:
bool withdraw(double amount);
bool deposit(double amount);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-2
Creating objects
Using the default constructor
Account frank_account;
Account jim_account;

Account *mary_account = new Account;


delete mary_account;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-3
Declaring a Class
Account – user-defined no-args constructor
class Account
{
private:
std::string name;
double balance;
public:
Account() {
name = "None";
balance = 0.0;
}
bool withdraw(double amount);
bool deposit(double amount);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-4
Declaring a Class
Account – no default constructor
class Account
{
private:
std::string name;
double balance;
public:
Account(std::string name_val, double bal) {
name = name_val;
balance = bal;
}
bool withdraw(double amount);
bool deposit(double amount);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-5
Creating objects
Using the default constructor

Account frank_account; // Error


Account jim_account; // Error

Account *mary_account = new Account; // Error


delete mary_account;

Account bill_account {"Bill", 15000.0}; // OK

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor S13-CPP-0180-6
Overloading Constructors
• Classes can have as many constructors as necessary

• Each must have a unique signature

• Default constructor is no longer compiler-generated once another constructor


is declared

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0200-1
Constructors and Destructors
Overloaded Constructors

class Player
{
private:
std::string name;
int health;
int xp;
public:
// Overloaded Constructors
Player();
Player(std::string name_val);
Player(std::string name_val, int health_val, int xp_val);
};
BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS
Overloading Constructors S13-CPP-0200-2
Constructors and Destructors
Overloaded Constructors

Player::Player() {
name = "None";
health = 0;
xp = 0;
}

Player::Player(std::string name_val) {
name = name_val;
health = 0;
xp = 0;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0200-3
Constructors and Destructors
Overloaded Constructors

Player::Player(std::string name_val, int health_val, int


xp_val) {
name = name_val;
health = health_val;
xp = xp_val;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0200-4
Creating objects
Player empty; // None, 0, 0

Player hero {"Hero"}; // Hero, 0, 0


Player villain {"Villain"}; // Villain, 0, 0

Player frank {"Frank", 100, 4}; // Frank, 100, 4

Player *enemy = new Player("Enemy", 1000, 0); // Enemy, 1000, 0


delete enemy;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0200-5
Constructor Initialization Lists
• So far, all data member values have been set in the constructor body

• Constructor initialization lists


• are more efficient
• initialization list immediately follows the parameter list
• initializes the data members as the object is created!
• order of initialization is the order of declaration in the class

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Initialization Lists S13-CPP-0220-1
Constructor Initialization Lists
class Player
{
private:
std::string name;
int health;
int xp;
public:
// Overloaded Constructors
Player();
Player(std::string name_val);
Player(std::string name_val, int health_val, int xp_val);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0220-2
Constructor Initialization Lists
Player()
Previous way:
Player::Player() {
name = "None"; // assignment not initialization
health = 0;
xp = 0;
}

Better way:
Player::Player()
: name{"None"}, health{0}, xp{0} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0220-3
Constructor Initialization Lists
Player(std::string)
Previous way:
Player::Player(std::string name_val) {
name = name_val; // assignment not initialization
health = 0;
xp = 0;
}

Better way:
Player::Player(std::string name_val)
: name{name_val}, health{0}, xp{0} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0220-4
Constructor Initialization Lists
Player(std::string, int, int)

Previous way:
Player::Player(std::string name_val, int health_val, int xp_val) {
name = name_val; // assignment not initialization
health = health_val;
xp = xp_val;
}

Better way:
Player::Player(std::string name_val, int health_val, int xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0220-5
Constructor Initialization Lists
Player::Player()
: name{"None"}, health{0}, xp{0} {
}

Player::Player(std::string name_val)
: name{name_val}, health{0}, xp{0} {
}

Player::Player(std::string name_val, int health_val, int


xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Overloading Constructors S13-CPP-0220-6
Delegating Constructors
• Often the code for constructors is very similar

• Duplicated code can lead to errors

• C++ allows delegating constructors


• code for one constructor can call another in the initialization list
• avoids duplicating code

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Delegating Constructors S13-CPP-0240-1
Delegating Constructors
class Player
{
private:
std::string name;
int health;
int xp;
public:
// Overloaded Constructors
Player();
Player(std::string name_val);
Player(std::string name_val, int health_val, int xp_val);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Delegating Constructors S13-CPP-0240-2
Delegating Constructors
Player::Player()
: name{"None"}, health{0}, xp{0} {
}

Player::Player(std::string name_val)
: name{name_val}, health{0}, xp{0} {
}

Player::Player(std::string name_val, int health_val, int


xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Delegating Constructors S13-CPP-0240-3
Delegating Constructors
Player::Player(std::string name_val, int health_val, int xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
}

Player::Player()
: Player {"None", 0, 0} {
}

Player::Player(std::string name_val)
: Player { name_val, 0, 0} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Delegating Constructors S13-CPP-0240-4
Default Constructor Parameters
• Can often simplify our code and reduce the number of overloaded
constructors

• Same rules apply as we learned with non-member functions

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor Parameters S13-CPP-0260-1
Default Constructor Parameters
class Player
{
private:
std::string name;
int health;
int xp;
public:
// Constructor with default parameter values
Player(std::string name_val = "None",
int health_val = 0,
int xp_val = 0);
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor Parameters S13-CPP-0260-2
Default Constructor Parameters

Player::Player(std::string name_val, int health_val, int


xp_val)
: name {name_val}, health {health_val}, xp {xp_val} {

}
Player empty; // None, 0, 0
Player frank {"Frank"}; // Frank, 0, 0
Player villain {"Villain", 100, 55}; // Villain, 100, 55
Player hero {"Hero", 100}; // Hero, 100, 0

// Note what happens if you declare a no-args constructor

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Default Constructor Parameters S13-CPP-0260-3
Copy Constructor
• When objects are copied C++ must create a new object from an existing object

• When is a copy of an object made?


• passing object by value as a parameter
• returning an object from a function by value
• constructing one object based on another of the same class

• C++ must have a way of accomplishing this so it provides a compiler-defined


copy constructor if you don’t

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-1
Pass object by-value
Player hero {"Hero", 100, 20};

void display_player(Player p) {
// p is a COPY of hero in this example
// use p
// Destructor for p will be called
}

display_player(hero);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-2
Return object by value
Player enemy;

Player create_super_enemy() {
Player an_enemy{"Super Enemy", 1000, 1000};
return an_enemy; // A COPY of an_enemy is returned
}

enemy = create_super_enemy();

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-3
Construct one object based on another
Player hero {"Hero", 100, 100};

Player another_hero {hero}; // A COPY of hero is made

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-4
Copy Constructor
• If you don’t provide your own way of copying objects by value then
the compiler provides a default way of copying objects

• Copies the values of each data member to the new object


• default memberwise copy

• Perfectly fine in many cases

• Beware if you have a pointer data member


• Pointer will be copied
• Not what it is pointing to
• Shallow vs. Deep copy – more in the next video

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-5
Best practices
• Provide a copy constructor when your class has raw pointer members

• Provide the copy constructor with a const reference parameter

• Use STL classes as they already provide copy constructors

• Avoid using raw pointer data members if possible

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-6
Declaring the Copy Constructor
Type::Type(const Type &source);

Player::Player(const Player &source);

Account::Account(const Account &source);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-7
Implementing the Copy Constructor

Type::Type(const Type &source) {


// code or initialization list to copy the object
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-8
Implementing the Copy Constructor
Player

Player::Player(const Player &source)


: name{source.name},
health {source.health},
xp {source.xp} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-9
Implementing the Copy Constructor
Account

Account::Account(const Account &source)


: name{source.name},
balance {source.balance} {
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Copy Constructor S13-CPP-0280-10
Shallow vs. Deep Copying
• Consider a class that contains a pointer as a data member

• Constructor allocates storage dynamically and initializes the pointer

• Destructor releases the memory allocated by the constructor

• What happens in the default copy constructor?

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-1
Default copy constructor
• memberwise copy

• Each data member is copied from the source object

• The pointer is copied NOT what it points to (shallow copy)

• Problem: when we release the storage in the destructor, the other object still
refers to the released storage!

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-2
Copy Constructor
Shallow

class Shallow {
private:
int *data; // POINTER
public:
Shallow(int d); // Constructor
Shallow(const Shallow &source); // Copy
Constructor
~Shallow(); // Destructor
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-3
Copy Constructor
Shallow constructor

Shallow::Shallow(int d) {
data = new int; // allocate storage
*data = d;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-4
Copy Constructor
Shallow destructor

Shallow::~Shallow() {
delete data; // free storage
cout << "Destructor freeing data" << endl;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-5
Copy Constructor
Shallow copy constructor

Shallow::Shallow(const Shallow &source)


: data(source.data) {
cout << "Copy constructor - shallow"
<< endl;
}

Shallow copy - only the pointer is copied - not what it is pointing to!
Problem: source and the newly created object BOTH point to the SAME data area!

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-6
Copy Constructor
Shallow – a simple method that expects a copy

Shallow::Shallow(const Shallow &source)


: data(source.data) {
cout << "Copy constructor - shallow"
<< endl;
}
Shallow copy - only the pointer is copied - not what it is pointing to!
Problem: source and the newly created object BOTH point to the SAME data area!

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-7
Copy Constructor
Sample main – will likely crash

int main() {
Shallow obj1 {100};
display_shallow(obj1);
// obj1’s data has been released!

obj1.set_data_value(1000);
Shallow obj2 {obj1};
cout << "Hello world" << endl;
return 0;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Shallow Copying S13-CPP-0300-8
User-provided copy constructor
• Create a copy of the pointed-to data

• Each copy will have a pointer to unique storage in the heap

• Deep copy when you have a raw pointer as a class data member

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-1
Copy Constructor
Deep
class Deep {
private:
int *data; // POINTER
public:
Deep(int d); // Constructor
Deep(const Deep &source); // Copy Constructor
~Deep(); // Destructor
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-2
Copy Constructor
Deep constructor

Deep::Deep(int d) {
data = new int; // allocate storage
*data = d;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-3
Copy Constructor
Deep constructor

Deep::~Deep() {
delete data; // free storage
cout << "Destructor freeing data" << endl;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-4
Copy Constructor
Deep constructor

Deep::Deep(const Deep &source)


{
data = new int; // allocate storage
*data = *source.data;
cout << "Copy constructor - deep"
<< endl;
}

Deep copy – create new storage and copy values

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-5
Copy Constructor
Deep copy constructor – delegating constructor

Deep::Deep(const Deep &source)


: Deep{*source.data} {
cout << "Copy constructor - deep"
<< endl;
}

Delegate to Deep(int) and pass in the int (*source.data)source is pointing to

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-6
Copy Constructor
Deep – a simple method that expects a copy

void display_deep(Deep s) {
cout << s.get_data_value() << endl;
}

When s goes out of scope the destructor is called and releases data.
No Problem: since the storage being releases is unique to s

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-7
Copy Constructor
Sample main – will not crash
int main() {
Deep obj1 {100};
display_deep(obj1);

obj1.set_data_value(1000);
Deep obj2 {obj1};

return 0;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Deep Copying S13-CPP-0320-8
Move Constructor
•Sometimes when we execute code the compiler creates unnamed temporary
values

int total {0};


total = 100 + 200;

•100 + 200 is evaluated and 300 stored in an unnamed temp value


•the 300 is then stored in the variable total
•then the temp value is discarded

•The same happens with objects as well

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-1
When is it useful?
• Sometimes copy constructors are called many times automatically due to the copy
semantics of C++

• Copy constructors doing deep copying can have a significant performance bottleneck

• C++11 introduced move semantics and the move constructor


• Move constructor moves an object rather than copy it

• Optional but recommended when you have a raw pointer

• Copy elision – C++ may optimize copying away completely (RVO-Return Value
Optimization)

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-2
r-value references
• Used in moving semantics and perfect forwarding

• Move semantics is all about r-value references

• Used by move constructor and move assignment operator to efficiently move


an object rather than copy it

• R-value reference operator (&&)

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-3
r-value references
int x {100}
int &l_ref = x; // l-value reference
l_ref = 10; // change x to 10

int &&r_ref = 200; // r-value ref


r_ref = 300; // change r_ref to 300

int &&x_ref = x; // Compiler error

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-4
l-value reference parameters

int x {100}; // x is an l-value

void func(int &num); // A

func(x); // calls A – x is an l-value


func(200); // Error – 200 is an r-value

error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-5
r-value reference parameters

int x {100}; // x is an l-value

void func(int &&num); // B

func(200); // calls B – 200 is an r-value


func(x); // ERROR - x is an l-value

error: cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-6
l-value and r-value reference parameters

int x {100}; // x is an l-value

void func(int &num); // A


void func(int &&num); // B

func(x); // calls A – x is an l-value


func(200); // calls B - 200 is an r-value

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-7
Example - Move class
class Move {
private:
int *data; // raw pointer
public:
void set_data_value(int d) { *data = d; }
int get_data_value() { return *data; }
Move(int d); // Constructor
Move(const Move &source); // Copy Constructor
~Move(); // Destructor
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-8
Move class copy constructor

Move::Move(const Move &source) {


data = new int;
*data = *source.data;
}

Allocate storage and copy

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-9
Inefficient copying

Vector<Move> vec;

vec.push_back(Move{10});
vec.push_back(Move{20});

Copy Constructors will be called to copy the temps

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-10
Inefficient copying
Constructor for: 10
Constructor for: 10
Copy constructor - deep copy for: 10
Destructor freeing data for: 10
Constructor for: 20
Constructor for: 20
Copy constructor - deep copy for: 20
Constructor for: 10
Copy constructor - deep copy for: 10
Destructor freeing data for: 10
Destructor freeing data for: 20

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-11
What does it do?
•Instead of making a deep copy of the move constrictor
•‘moves’ the resource
•Simply copies the address of the resource from source to the current object
•And, nulls out the pointer in the source pointer

•Very efficient

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-12
syntax - r-value reference

Type::Type(Type &&source);

Player::Player(Player &&source);

Move::Move(Move &&source);

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-13
Move class with move constructor
class Move {
private:
int *data; // raw pointer
public:
void set_data_value(int d) { *data = d; }
int get_data_value() { return *data; }
Move(int d); // Constructor
Move(const Move &source);// Copy Constructor
Move(Move &&source); // Move Constructor
~Move(); // Destructor
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-14
Move class move constructor

Move::Move(Move &&source)
: data{source.data} {
source.data = nullptr;
}

‘Steal’ the data and then null out the source pointer

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-15
efficient

Vector<Move> vec;

vec.push_back(Move{10});
vec.push_back(Move{20});

Move Constructors will be called for the temp r-values

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-16
efficient
Constructor for: 10
Move constructor - moving resource: 10
Destructor freeing data for nullptr
Constructor for: 20
Move constructor - moving resource: 20
Move constructor - moving resource: 10
Destructor freeing data for nullptr
Destructor freeing data for nullptr
Destructor freeing data for: 10
Destructor freeing data for: 20

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Move Constructor S13-CPP-0340-17
this pointer
•this is a reserved keyword

•Contains the address of the object - so it’s a pointer to the object

•Can only be used in class scope

•All member access is done via the this pointer

•Can be used by the programmer


•To access data member and methods
•To determine if two objects are the same (more in the next section)
•Can be dereferenced (*this) to yield the current object

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


This Pointer S13-CPP-0360-1
this pointer

void Account::set_balance(double bal) {


balance = bal; // this->balance is implied
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


This Pointer S13-CPP-0360-2
this pointer
To disambiguate identifier use

void Account::set_balance(double balance) {


balance = balance; // which balance? The parameter
}

void Account::set_balance(double balance) {


this->balance = balance; // Unambiguous
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


This Pointer S13-CPP-0360-3
this pointer
To determine object identity

•Sometimes its useful to know if two objects are the same object

int Account::compare_balance(const Account &other) {


if (this == &other)
std::cout << "The same objects" << std::endl;
...
}
frank_account.compare_balance(frank_account);

•We’ll use the this pointer again when we overload the assignment operator

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


This Pointer S13-CPP-0360-4
Using const with classes

• Pass arguments to class member methods as const

• We can also create const objects

• What happens if we call member functions on const objects?

• const-correctness

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-1
Creating a const object

•villain is a const object so it’s attributes cannot change

const Player villain {"Villain", 100, 55};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-2
Using const with classes
What happens when we call member methods on a const object?

const Player villain {"Villain", 100, 55};

villain.set_name("Nice guy"); // ERROR

std::cout << villain.get_name() << std::endl; // ERROR

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-3
Using const with classes
What happens when we call member methods on a const object?

const Player villain {"Villain", 100, 55};

void display_player_name(const Player &p) {


cout << p.get_name() << endl;
}

display_player_name(villain); // ERROR

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-4
Using const with classes
const methods

class Player {
private:
. . .
public:
std::string get_name() const;
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-5
Using const with classes
const-correctness

const Player villain {"Villain", 100, 55};

villain.set_name("Nice guy"); // ERROR

std::cout << villain.get_name() << std::endl; // OK

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-6
Using const with classes
const methods

class Player {
private:
. . .
public:
std::string get_name() const;
// ERROR if code in get_name modifies this object
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Using const with classes S13-CPP-0380-7
Static Class Members
•Class data members can be declared as static
•A single data member that belongs to the class, not the objects
•Useful to store class-wide information

•Class functions can be declared as static


•Independent of any objects
•Can be called using the class name

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-1
Player class -static members
class Player {
private:
static int num_players;

public:
static int get_num_players();
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-2
Player class – initialize the static data
Typically in Player.cpp

#include "Player.h"

int Player::num_players = 0;

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-3
Player class – implement static method

int Player::get_num_players() {
return num_players;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-4
Player class –update the constructor

Player::Player(std::string name_val, int health_val,


int xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {
++num_players;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-5
Player class - Destructor
Player::~Player() {
--num_players;
}

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-6
main.cpp
void display_active_players() {
cout << "Active players: "
<< Player::get_num_players() << endl;
}

int main() {
display_active_players();

Player obj1 {"Frank"};


display_active_players();
. . .

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Static Class Members S13-CPP-0400-7
Structs vs Classes

•In addition to define a class we can declare a struct

•struct comes from the C programming language

•Essentially the same as a class expect


•members are public by default

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Structs vs Classes S13-CPP-0420-1
class
class Person {
std::string name;
std::string get_name();
};

Person p;
p.name = "Frank"; // compiler error - private
std::cout << p.get_name(); // compiler error - private

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Structs vs Classes S13-CPP-0420-2
struct
struct Person {
std::string name;
std::string get_name(); // Why if name is public?
};

Person p;
p.name = "Frank"; // OK - public
std::cout << p.get_name(); // OK - public

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Structs vs Classes S13-CPP-0420-3
Some general guidelines

•struct
•Use struct for passive objects with public access
•Don’t declare methods in struct

•class
•Use class for active objects with private access
•Implement getters/setters as needed
•Implement member methods as needed

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Structs vs Classes S13-CPP-0420-4
Friends of a Class
•Friend
•A function or class that has access to private class member
•And, that function of or class is NOT a member of the class it is accessing

•Function
•Can be regular non-member functions
•Can be member methods of another class

•Class
•Another class can have access to private class members

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-1
Friends of a Class
•Friendship must be granted NOT taken
•Declared explicitly in the class that is granting friendship
•Declared in the function prototype with the keyword friend

•Friendship is not symmetric


•Must be explicitly granted
• if A is a friend of B
• B is NOT a friend of A

•Friendship is not transitive


•Must be explicitly granted
• if A is a friend of B AND
• B is a friend of C
• then A is NOT a friend of C

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-2
non-member function
class Player {
friend void display_player(Player &p);
std::string name;
int health;
int xp;
public:
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-3
non-member function

void display_player(Player &p) {


std::cout << p.name << std::endl;
std::cout << p.health << std::endl;
std::cout << p.xp << std::endl;
}

display_player may also change private data members

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-4
member function of another class

class Player {
friend void Other_class::display_player(Player &p);
std::string name;
int health;
int xp;
public:
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-5
member function of another class

class Other_class {
. . .
public:
void display_player(Player &p) {
std::cout << p.name << std::endl;
std::cout << p.health << std::endl;
std::cout << p.xp << std::endl;
}
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-6
Another class as a friend

class Player {
friend class Other_class;
std::string name;
int health;
int xp;
public:
. . .
};

BEGINNING C++ PROGRAMMING OOP - CLASSES AND OBJECTS


Friends of a Class S13-CPP-0440-7
Section Overview
Operator Overloading

• What is Operator Overloading?

• Overloading the assignment operator (=)


• Copy semantics
• Move semantics

• Overloading operators as member functions

• Overloading operators as global functions

• Overloading stream insertion (<<) and extraction operators (>>)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Section Overview S14-CPP-0020-1
Operator Overloading
What is Operator Overloading?

• Using traditional operators such as +, =, *, etc. with user-defined types

• Allows user defined types to behave similar to built-in types

• Can make code more readable and writable

• Not done automatically (except for the assignment operator)


They must be explicitly defined

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-1
Operator Overloading
What is Operator Overloading?

Suppose we have a Number class that models any number

•Using functions:

Number result = multiply(add(a,b),divide(c,d));

•Using member methods:

Number result = (a.add(b)).multiply(c.divide(d));

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-2
Operator Overloading
What is Operator Overloading?

Suppose we have a Number class that models any number

•Using overloaded operators

Number result = (a+b)*(c/d);

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-3
Operator Overloading
What operators can be overloaded?

•The majority of C++’s operators can be overloaded

•The following operators cannot be overload

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-4
Operator Overloading
Some basic rules

•Precedence and Associativity cannot be changed

•‘arity’ cannot be changed (i.e. can’t make the division operator unary)

•Can’t overload operators for primitive type (e.g. int, double, etc.)

•Can’t create new operators

•[], (), ->, and the assignment operator (=) must be declared as member methods

•Other operators can be declared as member methods or global functions

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-5
Operator Overloading
Some examples

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-6
Operator Overloading
Mystring class declaration

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator Overloading S14-CPP-0040-7
Operator Overloading
Copy assignment operator (=)

•C++ provides a default assignment operator used for assigning one object to
another

Mystring s1 {"Frank"};
Mystring s2 = s1; // NOT assignment
// same as Mystring s2{s1};

s2 = s1; // assignment

•Default is memberwise assignment (shallow copy)


•If we have raw pointer data member we must deep copy

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-1
Operator Overloading
Overloading the copy assignment operator (deep copy)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-2
Operator Overloading
Overloading the copy assignment operator (deep copy)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-3
Operator Overloading
Overloading the copy assignment operator – steps for deep copy

•Check for self assignment

if (this == &rhs) // p1 = p1;


return *this; // return current object

•Deallocate storage for this->str since we are overwriting it

delete [] str;

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-4
Operator Overloading
Overloading the copy assignment operator – steps for deep copy

•Allocate storage for the deep copy

str = new char[std::strlen(rhs.str) + 1];

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-5
Operator Overloading
Overloading the copy assignment operator – steps for deep copy

•Perform the copy

std::strcpy(str, rhs.str);

•Return the current by reference to allow chain assignment

return *this;

// s1 = s2 = s3;

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Copy Assignment Operator S14-CPP-0060-6
Operator Overloading
Move assignment operator (=)

•You can choose to overload the move assignment operator


•C++ will use the copy assignment operator if necessary

Mystring s1;

s1 = Mystring {"Frank"}; // move assignment

•If we have raw pointer we should overload the move assignment operator for
efficiency

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Move Assignment Operator S14-CPP-0080-1
Operator Overloading
Overloading the Move assignment operator

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Move Assignment Operator S14-CPP-0080-2
Operator Overloading
Overloading the Move assignment operator

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Move Assignment Operator S14-CPP-0080-3
Operator Overloading
Overloading the Move assignment operator – steps

•Check for self assignment

if (this == &rhs)
return *this; // return current object

•Deallocate storage for this->str since we are overwriting it

delete [] str;

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Move Assignment Operator S14-CPP-0080-4
Operator Overloading
Overloading the Move assignment operator – steps for deep copy

•Steal the pointer from the rhs object and assign it to this->str

str = rhs.str;

•Null out the rhs pointer

rhs.str = nullptr;

•Return the current object by reference to allow chain assignment

return *this;

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Move Assignment Operator S14-CPP-0080-5
Operator Overloading
Unary operators as member methods (++, --, -, !)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-1
Operator Overloading
Mystring operator- make lowercase

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-2
Operator Overloading
Mystring operator- make lowercase

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-3
Operator Overloading
Binary operators as member methods (+,-,==,!=,<,>, etc.)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-4
Operator Overloading
Mystring operator==

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-5
Operator Overloading
Mystring operator+ (concatenation)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-6
Operator Overloading
Mystring operator+ (concatenation)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Member Function S14-CPP-0100-7
Operator Overloading
Unary operators as global functions (++, --, -, !)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-1
Operator Overloading
Mystring operator- make lowercase

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-2
Operator Overloading
Mystring operator-

•Often declared as friend functions in the class declaration

Mystring operator-(const Mystring &obj) {


char *buff = new char[std::strlen(obj.str) + 1];
std::strcpy(buff, obj.str);
for (size_t i=0; i<std::strlen(buff); i++)
buff[i] = std::tolower(buff[i]);
Mystring temp {buff};
delete [] buff;
return temp;
}

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-3
Operator Overloading
Binary operators as global functions (+,-,==,!=,<,>, etc.)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-4
Operator Overloading
Mystring operator==

bool operator==(const Mystring &lhs, const Mystring &rhs){


if (std::strcmp(lhs.str, rhs.str) == 0)
return true;
else
return false;
}

•If declared as a friend of Mystring can access private str attribute


•Otherwise we must use getter methods

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-5
Operator Overloading
Mystring operator+ (concatenation)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-6
Operator Overloading
Mystring operator+ (concatenation)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Operator as Global Function S14-CPP-0120-7
Operator Overloading
stream insertion and extraction operators (<<, >>)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Overloading Insertion and Extraction S14-CPP-0140-1
Operator Overloading
stream insertion and extraction operators (<<, >>)

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Overloading Insertion and Extraction S14-CPP-0140-2
Operator Overloading
stream insertion and extraction operators (<<, >>)

•Doesn’t make sense to implement as member methods


•Left operand must be a user-defined class
•Not the way we normally use these operators

Mystring larry;
larry << cout; // huh?

Player hero;
hero >> cin; // huh?

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Overloading Insertion and Extraction S14-CPP-0140-3
Operator Overloading
stream insertion operator (<<)

std::ostream &operator<<(std::ostream &os, const Mystring &obj) {


os << obj.str; // if friend function
// os << obj.get_str(); // if not friend function
return os;
}

•Return a reference to the ostream so we can keep inserting


•Don’t return ostream by value!

BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING


Overloading Insertion and Extraction S14-CPP-0140-4
Operator Overloading
stream extraction operator (>>)

std::istream &operator>>(std::istream &is, Mystring &obj) {


char *buff = new char[1000];
is >> buff;
obj = Mystring{buff}; // If you have copy or move assignment
delete [] buff;
return is;
}

•Return a reference to the istream so we can keep inserting


•Update the object passed in
BEGINNING C++ PROGRAMMING OPERATOR OVERLOADING
Overloading Insertion and Extraction S14-CPP-0140-5
Section Overview
Inheritance

• What is Inheritance?
• Why is it useful?
• Terminology and Notation
• Inheritance vs. Composition
• Deriving classes from existing classes
• Types of inheritance
• Protected members and class access
• Constructors and Destructors
• Passing arguments to base class constructors
• Order of constructor and destructors calls
• Redefining base class methods
• Class Hierarchies
• Multiple Inheritance
BEGINNING C++ PROGRAMMING INHERITANCE
Section Overview S15-CPP-0020-1
Inheritance
What is it and why is it used?
• Provides a method for creating new classes from existing classes

• The new class contains the data and behaviors of the existing class

• Allow for reuse of existing classes

• Allows us to focus on the common attributes among a set of classes

• Allows new classes to modify behaviors of existing classes to make it unique


• Without actually modifying the original class

BEGINNING C++ PROGRAMMING INHERITANCE


What is Inheritance? S15-CPP-0040-1
Inheritance
Related classes
• Player, Enemy, Level Boss, Hero, Super Player, etc.

• Account, Savings Account, Checking Account, Trust Account, etc.

• Shape, Line, Oval, Circle, Square, etc.

• Person, Employee, Student, Faculty, Staff, Administrator, etc.

BEGINNING C++ PROGRAMMING INHERITANCE


What is Inheritance? S15-CPP-0040-2
Inheritance
Accounts

•Account
• balance, deposit, withdraw, . . .
•Savings Account
• balance, deposit, withdraw, interest rate, . . .
•Checking Account
• balance, deposit, withdraw, minimum balance, per check fee, . . .

•Trust Account
• balance, deposit, withdraw, interest rate, . . .

BEGINNING C++ PROGRAMMING INHERITANCE


What is Inheritance? S15-CPP-0040-3
Inheritance
Accounts – without inheritance – code duplication

BEGINNING C++ PROGRAMMING INHERITANCE


What is Inheritance? S15-CPP-0040-4
Inheritance
Accounts – with inheritance – code reuse

BEGINNING C++ PROGRAMMING INHERITANCE


What is Inheritance? S15-CPP-0040-5
Inheritance
Terminology

•Inheritance
• Process of creating new classes from existing classes
• Reuse mechanism
•Single Inheritance
• A new class is created from another ‘single’ class
•Multiple Inheritance
• A new class is created from two (or more) other classes

BEGINNING C++ PROGRAMMING INHERITANCE


Terminology and Notation S15-CPP-0060-1
Inheritance
Terminology

•Base class (parent class, super class)


• The class being extended or inherited from

•Derived class (child class, sub class)


• The class being created from the Base class
• Will inherit attributes and operations from Base class

BEGINNING C++ PROGRAMMING INHERITANCE


Terminology and Notation S15-CPP-0060-2
Inheritance
Terminology

•“Is-A” relationship
• Public inheritance
• Derived classes are sub-types of their Base classes
• Can use a derived class object wherever we use a base class object
•Generalization
• Combining similar classes into a single, more general class based on common attributes
•Specialization
• Creating new classes from existing classes proving more specialized attributes or operations
•Inheritance or Class Hierarchies
• Organization of our inheritance relationships

BEGINNING C++ PROGRAMMING INHERITANCE


Terminology and Notation S15-CPP-0060-3
Inheritance
Class hierarchy

Classes:
•A
• B is derived from A
• C is derived from A
• D is derived from C
• E is derived from D

BEGINNING C++ PROGRAMMING INHERITANCE


Terminology and Notation S15-CPP-0060-4
Inheritance
Class hierarchy

Classes:
• Person
• Employee is derived from Person
• Student is derived from Person
• Faculty is derived from Employee
• Staff is derived from Employee
• Administrator is derived from Employee

BEGINNING C++ PROGRAMMING INHERITANCE


Terminology and Notation S15-CPP-0060-5
Inheritance
Public Inheritance vs. Composition

•Both allow reuse of existing classes

•Public Inheritance
• “is-a” relationship
• Employee ‘is-a’ Person
• Checking Account ‘is-a’ Account
• Circle “is-a” Shape

•Composition
• “has-a” relationship
• Person “has a” Account
• Player “has-a” Special Attack
• Circle “has-a” Location

BEGINNING C++ PROGRAMMING INHERITANCE


Inheritance vs Composition S15-CPP-0080-1
Inheritance
Public Inheritance vs. Composition

has
Person Account

Employee Student

Faculty Staff Administrator

BEGINNING C++ PROGRAMMING INHERITANCE


Inheritance vs Composition S15-CPP-0080-2
Inheritance
Public Inheritance vs. Composition

class Person {
private:
std::string name; // has-a name
Account account; // has-a account
};

BEGINNING C++ PROGRAMMING INHERITANCE


Inheritance vs Composition S15-CPP-0080-3
Deriving classes from exiting classes
C++ derivation syntax
class Base {
// Base class members . . .
};

class Derived: access-specifier Base {


// Derived class members . . .
};

Access-specifier can be: public, private, or protected

BEGINNING C++ PROGRAMMING INHERITANCE


Deriving Classes from Exiting Classes S15-CPP-0100-1
Deriving classes from exiting classes
Types of inheritance in C++

•public
•Most common
•Establishes ‘is-a’ relationship between Derived and Base classes

•private and protected


•Establishes “derived class has a base class” relationship
•“Is implemented in terms of” relationship
•Different from composition

BEGINNING C++ PROGRAMMING INHERITANCE


Deriving Classes from Exiting Classes S15-CPP-0100-2
Deriving classes from exiting classes
C++ derivation syntax
class Account {
// Account class members . . .
};

class Savings_Account: public Account {


// Savings_Account class members . . .
};

Savings_Account ‘is-a’ Account

BEGINNING C++ PROGRAMMING INHERITANCE


Deriving Classes from Exiting Classes S15-CPP-0100-3
Deriving classes from exiting classes
C++ creating objects

Account account {};


Account *p_account = new Account();

account.deposit(1000.0);
p_account->withdraw(200.0);

delete p_account;

BEGINNING C++ PROGRAMMING INHERITANCE


Deriving Classes from Exiting Classes S15-CPP-0100-4
Deriving classes from exiting classes
C++ creating objects

Savings_Account sav_account {};


Savings_Account *p_sav_account = new Savings_Account();

sav_account.deposit(1000.0);
p_sav_account->withdraw(200.0);

delete p_sav_account;

BEGINNING C++ PROGRAMMING INHERITANCE


Deriving Classes from Exiting Classes S15-CPP-0100-5
Protected Members and Class Access
The protected class member modifier

class Base {

protected:
// protected Base class members . . .
};

•Accessible from the Base class itself


•Accessible from classes Derived from Base
•Not accessible by objects of Base or Derived

BEGINNING C++ PROGRAMMING INHERITANCE


Protected Members and Class Access S15-CPP-0120-1
Protected Members and Class Access
The protected class member modifier
class Base {
public:
int a; // public Base class members . . .

protected:
int b; // protected Base class members . . .

private:
int c; // private Base class members . . .

};

BEGINNING C++ PROGRAMMING INHERITANCE


Protected Members and Class Access S15-CPP-0120-2
Deriving classes from exiting classes
Access with public inheritance

BEGINNING C++ PROGRAMMING INHERITANCE


Protected Members and Class Access S15-CPP-0120-3
Deriving classes from exiting classes
Access with protected inheritance

BEGINNING C++ PROGRAMMING INHERITANCE


Protected Members and Class Access S15-CPP-0120-4
Deriving classes from exiting classes
Access with private inheritance

BEGINNING C++ PROGRAMMING INHERITANCE


Protected Members and Class Access S15-CPP-0120-5
Constructors and Destructors
Constructors and class initialization

•A Derived class inherits from its Base class

•The Base part of the Derived class MUST be initialized BEFORE the
Derived class is initialized

•When a Derived object is created


•Base class constructor executes then
•Derived class constructor executes

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-1
Constructors and Destructors
Constructors and class initialization

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-2
Constructors and Destructors
Constructors and class initialization

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-3
Constructors and Destructors
Destructors

•Class destructors are invoked in the reverse order as constructors

•The Derived part of the Derived class MUST be destroyed BEFORE the
Base class destructor is invoked

•When a Derived object is destroyed


•Derived class destructor executes then
•Base class destructor executes
•Each destructor should free resources allocated in it’s own constructors

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-4
Constructors and Destructors
Destructors

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-5
Constructors and Destructors
Destructors and class initialization

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-6
Constructors and Destructors
Constructors and class initialization

•A Derived class does NOT inherit


•Base class constructors
•Base class destructor
•Base class overloaded assignment operators
•Base class friend functions

•However, the derived class constructors, destructors, and overloaded


assignment operators can invoke the base-class versions

•C++11 allows explicit inheritance of base ‘non-special’ constructors with


•using Base::Base; anywhere in the derived class declaration
•Lots of rules involved, often better to define constructors yourself

BEGINNING C++ PROGRAMMING INHERITANCE


Constructors and Destructors S15-CPP-0140-7
Inheritance
Passing arguments to base class constructors

•The Base part of a Derived class must be initialized first

•How can we control exactly which Base class constructor is used during
initialization?

•We can invoke the whichever Base class constructor we wish in the initialization
list of the Derived class

BEGINNING C++ PROGRAMMING INHERITANCE


Passing Arguments to Base Class Constructors S15-CPP-0160-1
Inheritance
Passing arguments to base class constructors
class Base {
public:
Base();
Base(int);
. . .
};

Derived::Derived(int x)
: Base(x), {optional initializers for Derived} {
// code
}
BEGINNING C++ PROGRAMMING INHERITANCE
Passing Arguments to Base Class Constructors S15-CPP-0160-2
Constructors and Destructors
Constructors and class initialization
class Base {
int value;
public:
Base(): value{0} {
cout << "Base no-args constructor" << endl;
}
Base(int x) : value{x} {
cout << "int Base constructor" << endl;
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Passing Arguments to Base Class Constructors S15-CPP-0160-3
Constructors and Destructors
Constructors and class initialization
class Derived : public Base {
int doubled_value;
public:
Derived(): Base{}, doubled_value{0} {
cout << "Derived no-args constructor " << endl;
}
Derived(int x) : Base{x}, doubled_value {x*2} {
cout << "int Derived constructor " << endl;
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Passing Arguments to Base Class Constructors S15-CPP-0160-4
Constructors and Destructors
Constructors and class initialization
Output
Base base; Base no-args constructor

Base base{100}; int Base constructor

Derived derived; Base no-args constructor


Derived no-args constructor

Derived derived{100}; int Base constructor


int Derived constructor

BEGINNING C++ PROGRAMMING INHERITANCE


Passing Arguments to Base Class Constructors S15-CPP-0160-5
Inheritance
Copy/Move constructors and overloaded operator=

•Not inherited from the Base class

•You may not need to provide your own


• Compiler-provided versions may be just fine

•We can explicitly invoke the Base class versions from the Derived class

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-1
Inheritance
Copy constructor

•Can invoke Base copy constructor explicitly


•Derived object ‘other’ will be sliced

Derived::Derived(const Derived &other)


: Base(other), {Derived initialization list}
{
// code
}

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-2
Constructors and Destructors
Copy Constructors
class Base {
int value;
public:
// Same constructors as previous example

Base(const Base &other) :value{other.value} {


cout << "Base copy constructor" << endl;
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-3
Constructors and Destructors
Copy Constructors
class Derived : public Base {
int doubled_value;
public:
// Same constructors as previous example

Derived(const Derived &other)


: Base(other), doubled_value {other.doubled_value } {
cout << "Derived copy constructor " << endl;
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-4
Constructors and Destructors
operator=
class Base {
int value;
public:
// Same constructors as previous example
Base &operator=(const Base &rhs) {
if (this != &rhs) {
value = rhs.value; // assign
}
return *this;
}
};
BEGINNING C++ PROGRAMMING INHERITANCE
Copy Constructor And Assignment S15-CPP-0180-5
Constructors and Destructors
operator=
class Derived : public Base {
int doubled_value;
public:
// Same constructors as previous example
Derived &operator=(const Derived &rhs) {
if (this != &rhs) {
Base::operator=(rhs); // Assign Base part
doubled_value = rhs.doubled_value; // Assign Derived part
}
return *this;
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-6
Inheritance
Copy/Move constructors and overloaded operator=
•Often you do not need to provide your own

•If you DO NOT not define them in Derived


•then the compiler will create them and automatically and call the base class’s version

•If you DO provide Derived versions


• then YOU must invoke the Base versions explicitly yourself

•Be careful with raw pointers


•Especially if Base and Derived each have raw pointers
•Provide them with deep copy semantics

BEGINNING C++ PROGRAMMING INHERITANCE


Copy Constructor And Assignment S15-CPP-0180-7
Inheritance
Using and redefining Base class methods

•Derived class can directly invoke Base class methods

•Derived class can override or redefine Base class methods

•Very powerful in the context of polymorphism


(next section)

BEGINNING C++ PROGRAMMING INHERITANCE


Using And Refining Base Methods S15-CPP-0200-1
Inheritance
Using and redefining Base class methods
class Account {
public:
void deposit(double amount) { balance += amount; }
};

class Savings_Account: public Account {


public:
void deposit(double amount) { // Redefine Base class method
amount += some_interest;
Account::deposit(amount); // invoke call Base class method
}
};

BEGINNING C++ PROGRAMMING INHERITANCE


Using And Refining Base Methods S15-CPP-0200-2
Inheritance
Static binding of method calls

•Binding of which method to use is done at compile time


•Default binding for C++ is static
•Derived class objects will use Derived::deposit
•But, we can explicitly invoke Base::deposit from Derived::deposit
•OK, but limited – much more powerful approach is dynamic binding which we
will see in the next section

BEGINNING C++ PROGRAMMING INHERITANCE


Using And Refining Base Methods S15-CPP-0200-3
Inheritance
Static binding of method calls

Base b;
b.deposit(1000.0); // Base::deposit

Derived d;
d.deposit(1000.0); // Derived::deposit

Base *ptr = new Derived();


ptr->deposit(1000.0); // Base::deposit ????

BEGINNING C++ PROGRAMMING INHERITANCE


Using And Refining Base Methods S15-CPP-0200-4
Multiple Inheritance
Person
•A derived class inherits from two or more
Base classes at the same time

•The Base classes may belong to


Employee Student

unrelated class hierarchies

•A Department Chair
•Is-A Faculty and Faculty Administrator Staff

•Is-A Administrator

Department
Chair

BEGINNING C++ PROGRAMMING INHERITANCE


Multiple Inheritance S15-CPP-0240-1
Multiple Inheritance
C++ Syntax

class Department_Chair:
public Faculty, public Administrator {
. . .
};

•Beyond the scope of this course


•Some compelling use-cases
•Easily misused
•Can be very complex

BEGINNING C++ PROGRAMMING INHERITANCE


Multiple Inheritance S15-CPP-0240-2
Section Overview
Polymorphism and Inheritance

•What is Polymorphism?
•Using base class pointers
•Static vs. dynamic binding
•Virtual functions
•Virtual destructors
•The override and final specifiers
•Using base class references
•Pure virtual functions and abstract classes
•Abstract classes as interfaces

BEGINNING C++ PROGRAMMING INHERITANCE


Section Overview S15-CPP-0240-2
Section Overview
Polymorphism and Inheritance

•What is Polymorphism?
•Using base class pointers
•Static vs. dynamic binding
•Virtual functions
•Virtual destructors
•The override and final specifiers
•Using base class references
•Pure virtual functions and abstract classes
•Abstract classes as interfaces

BEGINNING C++ PROGRAMMING POLYMORPHISM


Section Overview S16-CPP-0020-1
Polymorphism
What is Polymorphism?
• Fundamental to Object-Oriented Programming

• Polymorphism
• Compile-time / early binding / static binding
• Run-time / late binding / dynamic binding

• Runtime polymorphism
• Being able to assign different meanings to the same function at run-time

• Allows us to program more abstractly


• Think general vs. specific
• Let C++ figure out which function to call at run-time

• Not the default in C++, run-time polymorphism is achieved via


• Inheritance
• Base class pointers or references
• virtual functions

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-1
Polymorphism
Types of Polymorphism in C++?

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-2
Polymorphism
An non-polymorphic example – Static Binding

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-3
Polymorphism
An non-polymorphic example – Static Binding

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-4
Polymorphism
A polymorphic example – Dynamic Binding

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-5
Polymorphism
A polymorphic example – Dynamic Binding

BEGINNING C++ PROGRAMMING POLYMORPHISM


What is Polymorphism? S16-CPP-0040-6
Polymorphism
Using a Base class pointer

•For dynamic polymorphism we must have:

•Inheritance
•Base class pointer or Base class reference
•virtual functions

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using a Base Class Pointer S16-CPP-0060-1
Polymorphism
Using a Base class pointer

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using a Base Class Pointer S16-CPP-0060-2
Polymorphism
Using a Base class pointer

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using a Base Class Pointer S16-CPP-0060-3
Polymorphism
Using a Base class pointer

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using a Base Class Pointer S16-CPP-0060-4
Polymorphism
Virtual functions
• Redefined functions are bound statically
• Overridden functions are bound dynamically
• Virtual functions are overridden
• Allow us to treat all objects generally as objects of the Base class

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Functions S16-CPP-0100-1
Polymorphism
Declaring virtual functions
• Declare the function you want to override as virtual in the Base class
• Virtual functions are virtual all the way down the hierarchy from this point
• Dynamic polymorphism only via Account class pointer or reference

class Account {
public:
virtual void withdraw(double amount);
. . .
};

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Functions S16-CPP-0100-2
Polymorphism
Declaring virtual functions
• Override the function in the Derived classes
• Function signature and return type must match EXACTLY
• Virtual keyword not required but is best practice
• If you don’t provide an overridden version it is inherited from it’s base class

class Checking : public Account {


public:
virtual void withdraw(double amount);
. . .
};
BEGINNING C++ PROGRAMMING POLYMORPHISM
Virtual Functions S16-CPP-0100-3
Polymorphism
Virtual Destructors
• Problems can happen when we destroy polymorphic objects
• If a derived class is destroyed by deleting its storage via the base class pointer
and the class a non-virtual destructor. Then the behavior is undefined in the
C++ standard.
• Derived objects must be destroyed in the correct order starting at the correct
destructor

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0120-1
Polymorphism
Virtual Destructors
• Solution/Rule:
• If a class has virtual functions
• ALWAYS provide a public virtual destructor
• If base class destructor is virtual then all derived class destructors are also virtual

class Account {
public:
virtual void withdraw(double amount);
virtual ~Account();
. . .
};

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0120-2
Polymorphism
The override specifier
• We can override Base class virtual functions
• The function signature and return must be EXACTLY the same
• If they are different then we have redefinition NOT overriding
• Redefinition is statically bound
• Overriding is dynamically bound
• C++11 provides an override specifier to have the compiler ensure overriding

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0140-1
Polymorphism
The override specifier

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0140-2
Polymorphism
The override specifier

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0140-3
Polymorphism
The override specifier

Base *p1 = new Base();


p1->say_hello(); // "Hello - I'm a Base class object"

Base *p2 = new Derived();


p2->say_hello(); // "Hello - I'm a Base class object"

•Not what we expected


•say_hello method signatures are different
•So Derived redefines say_hello instead of overriding it!

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0140-4
Polymorphism
The override specifier

BEGINNING C++ PROGRAMMING POLYMORPHISM


Virtual Destructor S16-CPP-0140-5
Polymorphism
The final specifier
• C++11 provides the final specifier
• When used at the class level
• Prevents a class from being derived from

• When used at the method level


• Prevents virtual method from being overridden in derived classes

BEGINNING C++ PROGRAMMING POLYMORPHISM


The Final Specifier S16-CPP-0160-1
Polymorphism
final class

BEGINNING C++ PROGRAMMING POLYMORPHISM


The Final Specifier S16-CPP-0160-2
Polymorphism
final method

BEGINNING C++ PROGRAMMING POLYMORPHISM


The Final Specifier S16-CPP-0160-3
Polymorphism
Using Base class references

• We can also use Base class references with dynamic polymorphism

• Useful when we pass objects to functions that expect a Base class reference

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using Base Class References S16-CPP-0180-1
Polymorphism
Using Base class references

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using Base Class References S16-CPP-0180-2
Polymorphism
Using Base class references

BEGINNING C++ PROGRAMMING POLYMORPHISM


Using Base Class References S16-CPP-0180-3
Polymorphism
Pure virtual functions and abstract classes

•Abstract class
• Cannot instantiate objects
• These classes are used as base classes in inheritance hierarchies
• Often referred to as Abstract Base Classes

•Concrete class
• Used to instantiate objects from
• All their member functions are defined
• Checking Account, Savings Account
• Faculty, Staff
• Enemy, Level Boss

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-1
Polymorphism
Pure virtual functions and abstract classes

•Abstract base class


• Too generic to create objects from
• Shape, Employee, Account, Player

• Serves as parent to Derived classes that may have objects

• Contains at least one pure virtual function

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-2
Polymorphism
Pure virtual functions and abstract classes

•Pure virtual function


• Used to make a class abstract

• Specified with “=0” in its declaration

virtual void function() = 0; // pure virtual function

• Typically do not provide implementations

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-3
Polymorphism
Pure virtual functions and abstract classes

•Pure virtual function


• Derived classes MUST override the base class

• If the Derived class does not override then the Derived class is also abstract

• Used when it doesn't make sense for a base class to have an implementation
• But concrete classes must implement it

virtual void draw() = 0; // Shape


virtual void defend() = 0; // Player

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-4
Polymorphism
Pure virtual functions and abstract classes

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-5
Polymorphism
Pure virtual functions and abstract classes

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-6
Polymorphism
Pure virtual functions and abstract classes

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-7
Polymorphism
Pure virtual functions and abstract classes

Abstract Base class

• Cannot be instantiated

Shape shape; // Error


Shape *ptr = new Shape(); // Error

• We can use pointers and references to dynamically refer to concrete classes derived from them

Shape *ptr = new Circle();


ptr->draw();
ptr->rotate();

BEGINNING C++ PROGRAMMING POLYMORPHISM


Pure Virtual and Abstract Classes S16-CPP-0240-8
Polymorphism
What is using a class as an interface?
•An abstract class that has only pure virtual functions

•These functions provide a general set of services to the user of the class

•Provided as public

•Each subclass is free to implement these services as needed

•Every service (method) must be implemented

•The service type information is strictly enforced

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-1
Polymorphism
A Printable example

•C++ does not provide true interfaces

•We use abstract classes and pure virtual functions to achieve it

•Suppose we want to be able to provide Printable support for any object we


wish without knowing it’s implementation at compile time

std::cout << any_object << std::endl;

• any_object must conform to the Printable interface

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-2
Polymorphism
An Printable example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-3
Polymorphism
An Printable example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-4
Polymorphism
An Printable example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-5
Polymorphism
A Shapes example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-6
Polymorphism
A Shapes example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-7
Polymorphism
A Shapes example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-8
Polymorphism
A Shapes example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-9
Polymorphism
A Shapes example

BEGINNING C++ PROGRAMMING POLYMORPHISM


Abstract Classes As Interfaces S16-CPP-0260-10
Section Overview
Smart Pointers
•Issues with raw pointers
•What are smart pointers?
•Concept of ownership and RAII
•C++ Smart Pointers
• Unique pointers (unique_ptr)
• Shared pointers (shared_ptr)
• Weak pointers (weak_ptr)

•Custom deleters

BEGINNING C++ PROGRAMMING SMART POINTERS


Section Overview S17-CPP-0020-1
Smart Pointers
Issues with Raw Pointers
•C++ provides absolute flexibility with memory management
• Allocation
• Deallocation
• Lifetime management

•Some potentially serious problems


• Uninitialized (wild) pointers
• Memory leaks
• Dangling pointers
• Not exception safe

•Ownership?
• Who owns the pointer?
• When should a pointer be deleted?

BEGINNING C++ PROGRAMMING SMART POINTERS


Issues with Raw Pointers S17-CPP-0040-1
Smart Pointers
What are they?
•Objects
•Can only point to heap-allocated memory
•Automatically call delete when no longer needed
•Adhere to RAII principles
•C++ Smart Pointers
• Unique pointers (unique_ptr)
• Shared pointers (shared_ptr)
• Weak pointers (weak_ptr)
• Auto pointers (auto_ptr) Deprecated – we will not discuss

BEGINNING C++ PROGRAMMING SMART POINTERS


What are Smart Pointers S17-CPP-0060-1
Smart Pointers
What are they?
• #include <memory>

•Defined by class templates


• Wrapper around a raw pointer
• Overloaded operators
• Dereference (*)
• Member selection (->)
• Pointer arithmetic not supported (++, --, etc.)

• Can have custom deleters

BEGINNING C++ PROGRAMMING SMART POINTERS


What are Smart Pointers S17-CPP-0060-2
Smart Pointers
A simple example

BEGINNING C++ PROGRAMMING SMART POINTERS


What are Smart Pointers S17-CPP-0060-3
Smart Pointers
RAII – Resource Acquisition Is Initialization
•Common idiom or pattern used in software design based on container object lifetime
•RAII objects are allocated on the stack
•Resource Acquisition
• Open a file
• Allocate memory
• Acquire a lock

•Is Initialization
• The resource is acquired in a constructor

•Resource relinquishing
• Happens in the destructor
• Close the file
• Deallocate the memory
• Release the lock

BEGINNING C++ PROGRAMMING SMART POINTERS


What are Smart Pointers S17-CPP-0060-4
Smart Pointers
unique_ptr
•Simple smart pointer – very efficient!

•unique_ptr<T>
• Points to an object of type T on the heap
• It is unique – there can only be one unique_ptr<T> pointing to the object on the heap
• Owns what it points to
• Cannot be assigned or copied
• CAN be moved
• When the pointer is destroyed, what it points to is automatically destroyed

BEGINNING C++ PROGRAMMING SMART POINTERS


Unique Pointers S17-CPP-0080-1
Smart Pointers
unique_ptr – creating, initializing and using

BEGINNING C++ PROGRAMMING SMART POINTERS


Unique Pointers S17-CPP-0080-2
Smart Pointers
unique_ptr – some other useful methods

BEGINNING C++ PROGRAMMING SMART POINTERS


Unique Pointers S17-CPP-0080-3
Smart Pointers
unique_ptr – user defined classes

BEGINNING C++ PROGRAMMING SMART POINTERS


Unique Pointers S17-CPP-0080-4
Smart Pointers
unique_ptr – vectors and move

BEGINNING C++ PROGRAMMING SMART POINTERS


Unique Pointers S17-CPP-0080-5
Smart Pointers
unique_ptr – make_unique (C++14)

More efficient – no calls to new or delete


BEGINNING C++ PROGRAMMING SMART POINTERS
Unique Pointers S17-CPP-0080-6
Smart Pointers
shared_ptr

•Provides shared ownership of heap objects

•shared_ptr<T>
•Points to an object of type T on the heap
•It is not unique – there can many shared_ptrs pointing to the same object on the
heap
•Establishes shared ownership relationship
•CAN be assigned and copied
•CAN be moved
•Doesn’t support managing arrays by default
•When the use count is zero, the managed object on the heap is destroyed

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-1
Smart Pointers
shared_ptr – creating, initializing and using

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-2
Smart Pointers
shared_ptr – some other useful methods

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-3
Smart Pointers
shared_ptr – user defined classes

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-4
Smart Pointers
shared_ptr – vectors and move

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-5
Smart Pointers
shared_ptr – make_shared (C++11)

•Use std::make_shared – it’s more efficient!


•All 3 pointers point to the SAME object on the heap!
•When the use_count becomes 0 the heap object is deallocated

BEGINNING C++ PROGRAMMING SMART POINTERS


Shared Pointers S17-CPP-0100-6
Smart Pointers
weak_ptr
•Provides a non-owning “weak” reference

• weak_ptr<T>
• Points to an object of type T on the heap
• Does not participate in owning relationship
• Always created from a shared_ptr
• Does NOT increment or decrement reference use count
• Used to prevent strong reference cycles which could prevent objects from being deleted

BEGINNING C++ PROGRAMMING SMART POINTERS


Weak Pointers S17-CPP-0120-1
Smart Pointers
weak_ptr – circular or cyclic reference
•A refers to B
•B refers to A
•Shared strong ownership prevents heap deallocation

BEGINNING C++ PROGRAMMING SMART POINTERS


Weak Pointers S17-CPP-0120-2
Smart Pointers
weak_ptr – circular or cyclic reference
•Solution – make one of the pointers non-owning or ‘weak’
•Now heap storage is deallocated properly

BEGINNING C++ PROGRAMMING SMART POINTERS


Weak Pointers S17-CPP-0120-3
Smart Pointers
Custom deleters

•Sometimes when we destroy a smart pointer we need more than to just


destroy the object on the heap

•These are special use-cases

•C++ smart pointers allow you to provide custom deleters

•Lots of way to achieve this


•Functions
•Lambdas
•Others. . .

BEGINNING C++ PROGRAMMING SMART POINTERS


Custom Deleters S17-CPP-0140-1
Smart Pointers
Custom deleters - function

BEGINNING C++ PROGRAMMING SMART POINTERS


Custom Deleters S17-CPP-0140-2
Smart Pointers
Custom deleters - function

BEGINNING C++ PROGRAMMING SMART POINTERS


Custom Deleters S17-CPP-0140-3
Smart Pointers
Custom deleters - lambda

BEGINNING C++ PROGRAMMING SMART POINTERS


Custom Deleters S17-CPP-0140-4
Section Overview
Exception Handling
•What is an Exception?

•What is Exception Handling?

•What do we throw and catch exceptions?

•How does it affect flow of control?

•Defining our own exception classes

•The Standard Library Exception Hierarchy


• std::exception and what()

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Section Overview S18-CPP-0020-1
Exception Handling
Basic concepts
• Exception handling
• dealing with extraordinary situations
• indicates that an extraordinary situation has been detected or has occurred
• program can deal with the extraordinary situations in a suitable manner

• What causes exceptions?


• insufficient resources
• missing resources
• invalid operations
• range violations
• underflows and overflows
• Illegal data and many others

• Exception safe
• when your code handles exceptions

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-1
Exception Handling
Terminology
•Exception
• an object or primitive type that signals that an error has occurred

•Throwing an exception (raising an exception)


• your code detects that an error has occurred or will occur
• the place where the error occurred may not know how to handle the error
• code can throw an exception describing the error to another part of the program that knows how to
handle the error

•Catching an exception (handle the exception)


• code that handles the exception
• may or may not cause the program to terminate

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-2
Exception Handling
C++ Syntax
•throw
• throws an exception
• followed by an argument

•try { code that may throw an exception }


• you place code that may throw an exception in a try block
• if the code throws an exception the try block is exited
• the thrown exception is handled by a catch handler
• if no catch handler exists the program terminates

•catch(Exception ex) { code to handle the exception }


• code that handles the exception
• can have multiple catch handlers
• may or may not cause the program to terminate

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-3
Exception Handling
Divide by zero example

•What happens if total is zero?


•crash, overflow?
•it depends

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-4
Exception Handling
Divide by zero example

•What happens if total is zero?


•crash, overflow?
•it depends

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-5
Exception Handling
Divide by zero example

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Basic Concepts and Example S18-CPP-0040-6
Exception Handling
Throwing an exception from a function
What do we return if total is zero?

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Throwing from a Function S18-CPP-0060-1
Exception Handling
Throwing an exception from a function
Throw an exception if we can’t complete successfully

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Throwing from a Function S18-CPP-0060-2
Exception Handling
Catching an exception thrown from a function

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Throwing from a Function S18-CPP-0060-3
Exception Handling
Throwing multiple exceptions from a function

What if a function can fail in several ways


•gallons is zero
•miles or gallons is negative

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Handling Multiple Exceptions S18-CPP-0080-1
Exception Handling
Throwing an exception from a function
Throw different type exceptions for each condition

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Handling Multiple Exceptions S18-CPP-0080-2
Exception Handling
Catching an exception thrown from a function

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Handling Multiple Exceptions S18-CPP-0080-3
Exception Handling
Catching any type of exception

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Handling Multiple Exceptions S18-CPP-0080-4
Exception Handling
Stack unwinding
If an exception is thrown but not caught in the current scope
C++ tries to find a handler for the exception by unwinding the stack

• Function in which the exception was not caught terminates


and is removed from the call stack

• If a try block was used to then catch blocks are checked for a match

• If no try block was used or the catch handler doesn’t match


stack unwinding occurs again

• If the stack is unwound back to main and no catch handler handles the exception
the program terminates

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Stack Unwinding S18-CPP-0100-1
Exception Handling
User-defined exceptions

We can create exception classes and throw instances of those classes

Best practice:
•throw an object not a primitive type
•throw an object by value
•catch an object by reference (or const reference)

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


User Defined Exceptions S18-CPP-0120-1
Exception Handling
Creating exception classes

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


User Defined Exceptions S18-CPP-0120-2
Exception Handling
Throwing user-defined exception classes

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


User Defined Exceptions S18-CPP-0120-3
Exception Handling
Catching user-defined exceptions

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


User Defined Exceptions S18-CPP-0120-4
Exception Handling
Class-level exceptions
Exceptions can also be thrown from within a class:

•Method
• These work the same way as they do for functions as we’ve seen

•Constructor
• Constructors may fail
• Constructors do not return any value
• Throw an exception in the constructor if you cannot initialize an object

•Destructor
• Do NOT throw exceptions from your destructor

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Class Level Exceptions S18-CPP-0140-1
Exception Handling
Class-level exceptions

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Class Level Exceptions S18-CPP-0140-2
Exception Handling
Class-level exceptions

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Class Level Exceptions S18-CPP-0140-3
Exception Handling
The C++ standard library exception class hierarchy

C++ provides a class hierarchy of exception classes


•std::exception is the base class
•all subclasses implement the what() virtual function
•we can create our own user-defined exception subclasses

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Standard Exceptions S18-CPP-0160-1
Exception Handling
The C++ standard library exception class hierarchy

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Standard Exceptions S18-CPP-0160-2
Exception Handling
Deriving our class from std::exception

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Standard Exceptions S18-CPP-0160-3
Exception Handling
Our modified Account class constructor

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Standard Exceptions S18-CPP-0160-4
Exception Handling
Creating an Account object

BEGINNING C++ PROGRAMMING EXCEPTION HANDLING


Standard Exceptions S18-CPP-0160-5
Section Overview
I/O and Streams

• Streams and I/O

• Stream manipulators

• Reading and writing to a text file

• Using string streams

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Section Overview S19-CPP-0020-1
Files, Streams and I/O
• C++ uses streams as an interface between the program and input and output
devices

• Independent of the actual device

• Sequence of bytes

• Input stream provides data to the program

• Output stream receives data from the program

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Streams and I/O S19-CPP-0040-1
Files, Streams and I/O

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Streams and I/O S19-CPP-0040-2
Files, Streams and I/O
Common header files

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Streams and I/O S19-CPP-0040-3
Files, Streams and I/O
Commonly used stream classes

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Streams and I/O S19-CPP-0040-4
Files, Streams and I/O
Global stream objects

• Global objects – initialized before main executes


• Best practice is to use cerr for error messages and clog for log messages.

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Streams and I/O S19-CPP-0040-5
Files, Streams and I/O
Stream manipulators

•Streams have useful member functions to control formatting

•Can be used on input and output streams

•The time of the effect on the stream varies

•Can be used as member functions or as a manipulato

std::cout.width(10); // member function


std::cout << std::setw(10); // manipulator

•We’ll focus on manipulator usage

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators S19-CPP-0060-1
Files, Streams and I/O
Common stream manipulators

• Boolean
• boolalpha , noboolalpha

• Integer
• dec, hex, oct, showbase, noshowbase, showpos, noshowpos, uppercase, nouppercase

• Floating point
• fixed, scientific, setprecision, showpoint, noshowpoint, showpos, noshowpos

• Field width, justification and fill


• setw, left, right, internal, setfill

• Others
• endl, flush, skipws, noskipws, ws

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators S19-CPP-0060-2
Files, Streams and I/O
Formatting boolean types

•Default when displaying boolean values is 1 or 0

•Sometimes the strings true or false are more appropriate

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Boolean S19-CPP-0080-1
Files, Streams and I/O
Formatting boolean types

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Boolean S19-CPP-0080-2
Files, Streams and I/O
Formatting boolean types

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Boolean S19-CPP-0080-3
Files, Streams and I/O
Formatting boolean types

• All further boolean output will be affected

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Boolean S19-CPP-0080-4
Files, Streams and I/O
Formatting boolean types

• Method version

• Reset to default

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Boolean S19-CPP-0080-5
Files, Streams and I/O
Formatting integer types

•Default when displaying integer values is:


•dec (base 10)
•noshowbase - prefix used to show hexadecimal or octal
•nouppercase - when displaying a prefix and hex values it will be lower case
•noshowpos – no ‘+’ is displayed for positive numbers

•These manipulators affect all further output to the stream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-1
Files, Streams and I/O
Formatting integer types - setting base

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-2
Files, Streams and I/O
Formatting integer types - showing the base

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-3
Files, Streams and I/O
Formatting integer types - display hex in uppercase

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-4
Files, Streams and I/O
Formatting integer types - displaying the positive sign

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-5
Files, Streams and I/O
Setting/resetting integer types

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Integer S19-CPP-0100-6
Files, Streams and I/O
Formatting floating point types

•Default when displaying floating point values is:


• setprecision – number of digits displayed (6)
• fixed – not fixed to a specific number of digits after the decimal point
• noshowpoint – trailing zeroes are not displayed
• nouppercase - when displaying in scientific notation
• noshowpos – no ‘+’ is displayed for positive numbers

•These manipulators affect all further output to the stream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-1
Files, Streams and I/O
Formatting floating point types - precision

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-2
Files, Streams and I/O
Formatting floating point types - precision

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-3
Files, Streams and I/O
Formatting floating point types - precision

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-4
Files, Streams and I/O
Formatting floating point types - fixed

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-5
Files, Streams and I/O
Formatting floating point types - fixed

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-6
Files, Streams and I/O
Formatting floating point types - scientific

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-7
Files, Streams and I/O
Formatting floating point types - scientific uppercase

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-8
Files, Streams and I/O
Formatting floating point types - displaying the positive sign

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-9
Files, Streams and I/O
Formatting floating point types - trailing zeroes

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-10
Files, Streams and I/O
Returning to general settings

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Floating Point S19-CPP-0120-11
Files, Streams and I/O
Field width, align and fill

•Default when displaying floating point values is:


• setw – not set by default
• left – when no field width, right - when using field width
• fill – not set by default – blank space is used

•Some of these manipulators affect only the next data element put on the stream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-1
Files, Streams and I/O
Defaults

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-2
Files, Streams and I/O
Defaults

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-3
Files, Streams and I/O
Field width - setw

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-4
Files, Streams and I/O
Field width - setw

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-5
Files, Streams and I/O
Field width - justification

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-6
Files, Streams and I/O
Field width - setw

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-7
Files, Streams and I/O
Filling fixed width - setfill

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-8
Files, Streams and I/O
Field width - setw

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Manipulators Align and Fill S19-CPP-0140-9
Files, Streams and I/O
Input files (fstream and ifstream)

fstream and ifstream are commonly used for input files

1. #include <fstream>
2. Declare an fstream or ifstream object
3. Connect it to a file on your file system (opens it for reading)
4. Read data from the file via the stream
5. Close the stream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-1
Files, Streams and I/O
Opening a file for reading with (fstream)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-2
Files, Streams and I/O
Opening a file for reading with (ifstream)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-3
Files, Streams and I/O
Opening a file for reading with open

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-4
Files, Streams and I/O
Check if file opened successfully (is_open)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-5
Files, Streams and I/O
Check if file opened successfully – test the stream object

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-6
Files, Streams and I/O
Closing a file

• Always close any open files to flush out any unwritten data

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-7
Files, Streams and I/O
Reading from files using (>>)

• We can use the extraction operator for formatted read


• Same way we used it with cin

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-8
Files, Streams and I/O
Reading from files using getline

• We can use getline to read the file one line at a time

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-9
Files, Streams and I/O
Reading text file one line at a time

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-10
Files, Streams and I/O
Reading text file one line at a time

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-11
Files, Streams and I/O
Reading text file one character at a time (get)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Reading from a Text File S19-CPP-0200-12
Files, Streams and I/O
Output files (fstream and ofstream)

fstream and ofstream are commonly used for output files

1. #include <fstream>
2. Declare an fstream or ofstream object
3. Connect it to a file on your file system (opens it for writing)
4. Write data to the file via the stream
5. Close the stream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-1
Files, Streams and I/O
Output files (fstream and ofstream)

fstream and ofstream are commonly used for output files

• Output files will be created if they don’t exist


• Output files will be overwritten (truncated) by default
• Can be opened so that new writes append
• Can be open in text or binary modes

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-2
Files, Streams and I/O
Opening a file for writing with (fstream)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-3
Files, Streams and I/O
Opening a file for writing with (ofstream)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-4
Files, Streams and I/O
Opening a file for writing with (ofstream)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-5
Files, Streams and I/O
Opening a file for writing with open

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-6
Files, Streams and I/O
Check if file opened successfully (is_open)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-7
Files, Streams and I/O
Check if file opened successfully – test the stream object

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-8
Files, Streams and I/O
Closing a file

• Always close any open files to flush out any unwritten data

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-9
Files, Streams and I/O
Writing to files using (<<)
• We can use the insertion operator for formatted write
• Same way we used it with cout

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-10
Files, Streams and I/O
Copying a text file one line at a time

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-11
Files, Streams and I/O
Copying a text file one line at a time

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-12
Files, Streams and I/O
Copying a text file one character at a time (get/put)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-13
Files, Streams and I/O
Copying a text file one character at a time (get/put)

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Writing to a Text File S19-CPP-0340-14
Files, Streams and I/O
Using string streams
• Allow us to read or write from strings in memory much as we would read and write to
files

• Very powerful

• Very useful for data validation

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Using String Streams S19-CPP-0420-1
Files, Streams and I/O
Using string streams

stringstream, istringstream and ostringstream

1. #include <sstream>
2. Declare an stringstream, istringstream or ostringstream object
3. Connect it to a std::string
4. Read/write data from/to the string stream using formatted I/O

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Using String Streams S19-CPP-0420-2
Files, Streams and I/O
Reading from a stringstream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Using String Streams S19-CPP-0420-3
Files, Streams and I/O
Writing to a stringstream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Using String Streams S19-CPP-0420-4
Files, Streams and I/O
Validating input with stringstream

BEGINNING C++ PROGRAMMING I/O AND STREAMS


Using String Streams S19-CPP-0420-5
Files, Streams and I/O
File Locations and IDEs

BEGINNING C++ PROGRAMMING I/O AND STREAMS


File Locations and IDEs S19-CPP-0440-1
Files, Streams and I/O
File Locations and IDEs

Windows Visual Studio

BEGINNING C++ PROGRAMMING I/O AND STREAMS


File Locations and IDEs S19-CPP-0440-2
Files, Streams and I/O
File Locations and IDEs

Code::Blocks

BEGINNING C++ PROGRAMMING I/O AND STREAMS


File Locations and IDEs S19-CPP-0440-3
Files, Streams and I/O
File Locations and IDEs

CLion

BEGINNING C++ PROGRAMMING I/O AND STREAMS


File Locations and IDEs S19-CPP-0440-4
Files, Streams and I/O
File Locations and IDEs

Xcode

BEGINNING C++ PROGRAMMING I/O AND STREAMS


File Locations and IDEs S19-CPP-0440-5
Section Overview
The Standard Template Library
•What is the STL •Array
•Generic programming/ •Vector
Meta-programming •Deque
•Preprocessor macros
•Function templates •List and Forward List
•Class templates •Set and Multi Set
•STL Containers •Map and Multi Map
•STL Iterators •Stack and Queue
•STL Algorithms •Priority Queue
•Algorithms

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Section Overview S20-CPP-0020-1
What is the STL?
• A library of powerful, reusable, adaptable, generic classes and functions

• Implemented using C++ templates

• Implements common data structures and algorithms

• Huge class library!!

• Alexander Stepanov (1994)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-1
Why use the STL?
• Assortment of commonly used containers

• Known time and size complexity

• Tried and tested – Reusability!!!

• Consistent, fast, and type-safe

• Extensible

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-2
Elements of the STL
•Containers
•Collections of objects or primitive types
(array, vector, deque, stack, set, map, etc.)

•Algorithms
•Functions for processing sequences of elements from containers
(find, max, count, accumulate, sort, etc.)

•Iterators
•Generate sequences of element from containers
(forward, reverse, by value, by reference, constant, etc.)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-3
Elements of the STL
A simple example

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-4
Elements of the STL
A simple example – sort a vector

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-5
Elements of the STL
A simple example – reverse a vector

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-6
Elements of the STL
A simple example - accumulate

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-7
Types of Containers
•Sequence containers
•array, vector, list, forward_list, deque

•Associative containers
•set, multi set, map, multi map

•Container adapters
•stack, queue, priority queue

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-8
Types of Iterators
• Input iterators – from the container to the program

• Output iterators – from the program to the container

• Forward iterators – navigate one item at a time in one direction

• Bi-directional iterators – navigate one item at a time both directions

• Random access iterators – directly access a container item

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-9
Types of Algorithms
• About 60 algorithms in the STL

• Non-modifying

• Modifying

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


What is the STL? S20-CPP-0030-10
The Standard Template Library
Generic Programming with macros

•Generic programming
“Writing code that works with a variety of types as arguments,
as long as those argument types meet specific syntactic and
semantic requirements”, Bjarne Stroustrup

•Macros*** beware ***

•Function templates

•Class templates

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-1
The Standard Template Library
Macros (#define)

•C++ preprocessor directives


•No type information
•Simple substitution

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-2
The Standard Template Library
Macros (#define)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-3
The Standard Template Library
Macros (#define)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-4
The Standard Template Library
max function

• Suppose we need a function to determine the max of 2 integers

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-5
The Standard Template Library
max function

• Now suppose we need to determine the max of 2 doubles, and 2 chars

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-6
The Standard Template Library
Macros with argument s (#define)

• We can write a generic macro with arguments instead

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-7
The Standard Template Library
Macros with argument s (#define)

• We have to be careful with macros

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-8
The Standard Template Library
Macros with argument s (#define)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Macros S20-CPP-0040-9
The Standard Template Library
Generic Programming with function templates

What is a C++ Template?

• Blueprint

• Function and class templates

• Allow plugging-in any data type

• Compiler generates the appropriate function/class from the blueprint

• Generic programming / meta-programming

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-1
The Standard Template Library
Generic Programming with function templates

• Let’s revisit the max function from the last lecture

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-2
The Standard Template Library
max function

• Now suppose we need to determine the max of 2 doubles, and 2 chars

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-3
The Standard Template Library
max function as a template function

• We can replace type we want to generalize with a name, say T

• But now this won’t compile

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-4
The Standard Template Library
max function as a template function

• We need to tell the compiler this is a template function

• We also need to tell it that T is the template parameter

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-5
The Standard Template Library
max function as a template function

• We may also use class instead of typename

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-6
The Standard Template Library
max function as a template function

• Now the compiler can generate the appropriate function from the template

• Note, this happens at compile-time!

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-7
The Standard Template Library
max function as a template function

• Many times the compiler can deduce the type and the template parameter is
not needed

• Depending on the type of a and b, the compiler will figure it out

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-8
The Standard Template Library
max function as a template function

• And we can use almost any type we need

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-9
The Standard Template Library
max function as a template function

• Notice the type MUST support the > operator either natively or as an
overloaded operator (operator>)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-10
The Standard Template Library
max function as a template function

• The following will not compile unless Player overloads operator>

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-11
The Standard Template Library
multiple types as template parameters

• We can have multiple template parameters

• And their types can be different

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-12
The Standard Template Library
multiple types as template parameters

• When we use the function we provide the template parameters

• Often the compiler can deduce them

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Function Templates S20-CPP-0060-13
The Standard Template Library
Generic Programming with class templates

What is a C++ Class Template?

• Similar to function template, but at the class level

• Allows plugging-in any data type

• Compiler generates the appropriate class from the blueprint

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-1
The Standard Template Library
Generic Programming with class templates

• Let’s say we want a class to hold Items where the item has a name and an
integer

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-2
The Standard Template Library
Generic Programming with class templates

• But we’d like our Item class to be able to hold any type of data in addition to
the string

• We can’t overload class names

• We don’t want to use dynamic polymorphism

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-3
The Standard Template Library
Generic Programming with class templates

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-4
The Standard Template Library
Generic Programming with class templates

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-5
The Standard Template Library
Generic Programming with class templates

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-6
The Standard Template Library
Multiple types as template parameters

• We can have multiple template parameters

• An their types can be different

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-7
The Standard Template Library
Multiple types as template parameters

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-8
The Standard Template Library
std::pair

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


Generic Class Templates S20-CPP-0080-9
The Standard Template Library
Containers

•Data structures that can store object of almost any type


• Template-based classes

•Each container has member functions


• Some are specific to the container
• Others are available to all containers

•Each container has an associated header file


• #include <container_type>

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Containers S20-CPP-0100-1
The Standard Template Library
Containers – common

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Containers S20-CPP-0100-2
The Standard Template Library
Containers – common

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Containers S20-CPP-0100-3
The Standard Template Library
Container elements

What types of elements can we store in containers?

•A copy of the element will be stored in the container


•All primitives OK

•Element should be
•Copyable and assignable (copy constructor / copy assignment)
•Moveable for efficiency (move Constructor / move Assignment)

•Ordered associative containers must be able to compare elements


•operator<, operator==

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Containers S20-CPP-0100-4
The Standard Template Library
Iterators

• Allows abstracting an arbitrary container as a sequence of elements

• They are objects that work like pointers by design

• Most container classes can be traversed with iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-1
The Standard Template Library
Declaring iterators

• Iterators must be declared based on the container type


they will iterate over

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-2
The Standard Template Library
iterator begin and end methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-3
The Standard Template Library
Declaring iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-4
The Standard Template Library
Initializing iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-5
The Standard Template Library
Operations with iterators (it)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-6
The Standard Template Library
Using iterators – std::vector

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-7
The Standard Template Library
Using iterators – std::vector

• This is how the range-based for loop works


BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)
STL Iterators S20-CPP-0120-8
The Standard Template Library
Using iterators – std::set

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-9
The Standard Template Library
Reverse iterators

•Works in reverse
•Last element is the first and first is the last
•++ moves backward, -- moves forward

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-10
The Standard Template Library
Other iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Iterators S20-CPP-0120-11
The Standard Template Library
Algorithms

•STL algorithms work on sequences of container elements


provided to them by an iterator

•STL has many common and useful algorithms

•Too many to describe in this section


• http://en.cppreference.com/w/cpp/algorithm

•Many algorithms require extra information in order to do their work


• Functors (function objects)
• Function pointers
• Lambda expressions (C++11)

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-1
The Standard Template Library
Algorithms and iterators

•#include <algorithm>

•Different containers support different types of iterators


• Determines the types of algorithms supported

•All STL algorithms expect iterators as arguments


• Determines the sequence obtained from the container

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-2
The Standard Template Library
Iterator invalidation

•Iterators point to container elements

•It’s possible iterators become invalid during processing

•Suppose we are iterating over a vector of 10 elements


• And we clear() the vector while iterating? What happens?
• Undefined behavior – our iterators are pointing to invalid locations

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-3
The Standard Template Library
Example algorithm – find with primitive types

•The find algorithm tries to locate the first occurrence of an element in a


container
•Lots of variations
•Returns an iterator pointing to the located element or end()

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-4
The Standard Template Library
Example algorithm – find with user-defined types

•Find needs to be able to compare object

•operator== is used and must be provided by your class

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-5
The Standard Template Library
Example algorithm – for_each

•for_each algorithm applies a function to each element in the iterator


sequence

•Function must be provided to the algorithm as:


•Functor (function object)
•Function pointer
•Lambda expression (C++11)

•Let’s square each element

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-6
The Standard Template Library
for_each - using a functor

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-7
The Standard Template Library
for_each - using a function pointer

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-8
The Standard Template Library
for_each - using a lambda expression

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Algorithms S20-CPP-0140-9
The Standard Template Library
std::array (C++11)

#include <array>

• Fixed size
• Size must be known at compile time

• Direct element access

• Provides access to the underlying raw array

• Use instead of raw arrays when possible

• All iterators available and do not invalidate

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Array S20-CPP-0160-1
The Standard Template Library
std::array – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Array S20-CPP-0160-2
The Standard Template Library
std::array – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Array S20-CPP-0160-3
The Standard Template Library
std::array – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Array S20-CPP-0160-4
The Standard Template Library
std::vector

#include <vector>

• Dynamic size
• Handled automatically
• Can expand and contract as needed
• Elements are stored in contiguous memory as an array

• Direct element access (constant time)

• Rapid insertion and deletion at the back (constant time)

• Insertion or removal of elements (linear time)

• All iterators available and may invalidate

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-1
The Standard Template Library
std::vector

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-2
The Standard Template Library
std::vector

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-3
The Standard Template Library
std::vector – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-4
The Standard Template Library
std::vector – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-5
The Standard Template Library
std::vector – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-6
The Standard Template Library
std::vector – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-7
The Standard Template Library
std::vector – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Vector S20-CPP-0180-8
The Standard Template Library
std::deque (double ended queue)

#include <deque>

• Dynamic size
• Handled automatically
• Can expand and contract as needed
• Elements are NOT stored in contiguous memory

• Direct element access (constant time)

• Rapid insertion and deletion at the front and back (constant time)

• Insertion or removal of elements (linear time)

• All iterators available and may invalidate

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-1
The Standard Template Library
std::deque – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-2
The Standard Template Library
std::deque

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-3
The Standard Template Library
std::deque

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-4
The Standard Template Library
std::deque

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-5
The Standard Template Library
std::deque

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-6
The Standard Template Library
std::deque – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-7
The Standard Template Library
std::deque – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Deque S20-CPP-0200-8
The Standard Template Library
std::list and std::forward_list

•Sequence containers

•Non-contiguous in memory

•No direct access to elements

•Very efficient for inserting and deleting elements once an element is found

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-1
The Standard Template Library
std::list

#include <list>

•Dynamic size
• Lists of elements
• list is bidirectional (doubly-linked)

•Direct element access is NOT provided

•Rapid insertion and deletion of elements anywhere in the container


(constant time)

•All iterators available and invalidate when corresponding element is deleted

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-2
The Standard Template Library
std::list

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-3
The Standard Template Library
std::list – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-4
The Standard Template Library
std::list – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-5
The Standard Template Library
std::list – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-6
The Standard Template Library
std::list – methods that use iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-7
The Standard Template Library
std::list – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-8
The Standard Template Library
std::forward_list

#include <forward_list>

• Dynamic size
• Lists of elements
• list uni-directional (singly-linked)
• Less overhed than a std::list

• Direct element access is NOT provided

• Rapid insertion and deletion of elements anywhere in the container


(constant time)

• Reverse iterators not available. Iterators invalidate when corresponding element is deleted

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-9
The Standard Template Library
std::forward_list

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-10
The Standard Template Library
std::forward_list – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-11
The Standard Template Library
std::forward_list – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-12
The Standard Template Library
std::forward_list – methods that use iterators

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Lists S20-CPP-0260-13
The Standard Template Library
The STL Set containers

•Associative containers
•Collection of stored objects that allow fast retrieval using a key
•STL provides Sets and Maps
•Usually implemented as a balanced binary tree or hashsets
•Most operations are very efficient

•Sets
•std::set
•std::unordered_set
•std::multiset
•std::unordered_multiset

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-1
The Standard Template Library
std::set

#include <set>

•Similar to a mathematical set

•Ordered by key

•No duplicate elements

•All iterators available and invalidate when corresponding element is deleted

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-2
The Standard Template Library
std::set – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-3
The Standard Template Library
std::set – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-4
The Standard Template Library
std::set – common methods

•uses operator< for ordering!


•returns a std::pair<iterator, bool>
•first is an iterator to the inserted element or to the duplicate in the set
•second is a boolean indicating success or failure

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-5
The Standard Template Library
std::set – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-6
The Standard Template Library
std::set – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-7
The Standard Template Library
std::multi_set

#include <set>

•Sorted by key

•Allows duplicate elements

•All iterators are available

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-8
The Standard Template Library
std::unordered_set

#include <unordered_set>

•Elements are unordered

•No duplicate elements allowed

•Elements cannot be modified


• Must be erased and new element inserted

•No reverse iterators are allowed

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-9
The Standard Template Library
std::unordered_multiset

#include <unordered_set>

•Elements are unordered

•Allows duplicate elements

•No reverse iterators are allowed

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Sets S20-CPP-0320-10
The Standard Template Library
The STL Map containers

•Associative containers
•Collection of stored objects that allow fast retrieval using a key
•STL provides Sets and Maps
•Usually implemented as a balanced binary tree or hashsets
•Most operations are very efficient

•Maps
•std::map
•std::unordered_map
•std::multimap
•std::unordered_multimap

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-1
The Standard Template Library
std::map

#include <map>

• Similar to a dictionary

• Elements are stored as Key, Value pairs (std::pair)

• Ordered by key

• No duplicate elements (keys are unique)

• Direct element access using the key

• All iterators available and invalidate when corresponding element is deleted

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-2
The Standard Template Library
std::map – initialization and assignment

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-3
The Standard Template Library
std::map – common methods

•No concept of front and back


BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)
STL Maps S20-CPP-0340-4
The Standard Template Library
std::map – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-5
The Standard Template Library
std::map – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-6
The Standard Template Library
std::map – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-7
The Standard Template Library
std::map – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-8
The Standard Template Library
std::multi_map

#include <map>

•Ordered by key

•Allows duplicate elements

•All iterators are available

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-9
The Standard Template Library
std::unordered_map

#include <unordered_map>

•Elements are unordered

•No duplicate elements allowed

•No reverse iterators are allowed

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-10
The Standard Template Library
std::unordered_multimap

#include <unordered_map>

•Elements are unordered

•Allows duplicate elements

•No reverse iterators are allowed

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Maps S20-CPP-0340-11
The Standard Template Library
std::stack

•Last-in First-out (LIFO) data structure

•Implemented as an adapter over other STL container


Can be implemented as a vector, list, or deque

•All operations occur on one end of the stack (top)

•No iterators are supported

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Stack S20-CPP-0400-1
The Standard Template Library
std::stack

#include <stack>

•push – insert an element at the top of the stack


•pop – remove an element from the top of the stack
•top – access the top element of the stack
•empty – is the stack empty?
•size – number of elements in the stack

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Stack S20-CPP-0400-2
The Standard Template Library
std::stack – initialization

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Stack S20-CPP-0400-3
The Standard Template Library
std::stack – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Stack S20-CPP-0400-4
The Standard Template Library
std::stack – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Stack S20-CPP-0400-5
The Standard Template Library
std::queue

•First-in First-out (FIFO) data structure

•Implemented as an adapter over other STL container


Can be implemented as a list or deque

•Elements are pushed at the back and


popped from the front

•No iterators are supported

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Queue S20-CPP-0420-1
The Standard Template Library
std::queue

#include <queue>

•push – insert an element at the back of the queue


•pop – remove an element from the front of the queue

•front – access the element at the front


•back – access the element at the back

•empty – is the queue empty?


•size – number of elements in the queue

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Queue S20-CPP-0420-2
The Standard Template Library
std::queue – initialization

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Queue S20-CPP-0420-3
The Standard Template Library
std::queue – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Queue S20-CPP-0420-4
The Standard Template Library
std::queue – common methods

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Queue S20-CPP-0420-5
The Standard Template Library
std::priority_queue

•Allows insertions and removal of elements in order from the front of the
container

•Elements are stored internally as a vector by default

•Elements are inserted in priority order


(largest value will always be at the front)

•No iterators are supported

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Priority Queue S20-CPP-0480-1
The Standard Template Library
std::priority_queue

#include <queue>

•push – insert an element into sorted order


•pop – removes the top element (greatest)

•top – access the top element (greatest)

•empty – is the queue empty?


•size – number of elements in the queue

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Priority Queue S20-CPP-0480-2
The Standard Template Library
std::priority_queue – initialization

BEGINNING C++ PROGRAMMING THE STANDARD TEMPLATE LIBRARY (STL)


STL Priority Queue S20-CPP-0480-3
Bonus Section Overview
C++ Lambda expressions

•What is a lambda expression?


•Motivation
•Review of function objects (functors)
•Relation between lambdas and function objects
•Structure of a lambda expression
•Types of lambda expressions
•Stateless lambda expression
•Stateful lambda expression (capturing context)
•Lambdas and the STL

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Section Overview S21-CPP-0020-1
C++ Lambda Expressions
Motivation

•Prior to C++ 11
•Function objects
•Function pointers

•We often write many short functions that control algorithms

•These short functions would be encapsulated in small classes to produce function


objects

•Many times the classes and functions are far removed from where they are used
leading to modification, maintenance, and testing issues

•Compiler cannot effectively inline these functions for efficiency.

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-1
Motivation
Function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-2
Motivation
Function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-3
Motivation
Function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-4
Motivation
Generic function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-5
Motivation
Generic function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-6
Motivation
Generic function objects

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-7
Motivation
Using a lambda expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Motivation S21-CPP-0040-8
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-1
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-2
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-3
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-4
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-5
C++ Lambda Expressions
The Structure of a Lambda Expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-6
C++ Lambda Expressions
A simple lambda expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-7
C++ Lambda Expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-8
C++ Lambda Expressions
Parameters to lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-9
C++ Lambda Expressions
Parameters to lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-10
C++ Lambda Expressions
Assigning a lambda expression to a variable

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-11
C++ Lambda Expressions
Assigning a lambda expression to a variable

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-12
C++ Lambda Expressions
Returning a value from a lambda expression

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Structure of a Lambda Expression S21-CPP-0060-13
C++ Stateless Lambda Expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-1
C++ Stateless Lambda Expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-2
C++ Stateless Lambda Expressions
Simple stateless lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-3
C++ Stateless Lambda Expressions
Simple stateless lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-4
C++ Stateless Lambda Expressions
Simple stateless lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-5
C++ Stateless Lambda Expressions
Using values and references as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-6
C++ Stateless Lambda Expressions
Using values and references as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-7
C++ Stateless Lambda Expressions
Using values and references as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-8
C++ Stateless Lambda Expressions
Using pointers as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-9
C++ Stateless Lambda Expressions
Using pointers as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-10
C++ Stateless Lambda Expressions
Using pointers as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-11
C++ Stateless Lambda Expressions
Using pointers as lambda parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-12
C++ Stateless Lambda Expressions
Using arrays and vectors as lambda reference parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-13
C++ Stateless Lambda Expressions
Using auto as lambda parameter type specifiers

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-14
C++ Stateless Lambda Expressions
Using auto as lambda parameter type specifiers

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-15
C++ Stateless Lambda Expressions
Using auto as lambda parameter type specifiers

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-16
C++ Stateless Lambda Expressions
Using lambda expressions as function parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-17
C++ Stateless Lambda Expressions
Using lambda expressions as function parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-18
C++ Stateless Lambda Expressions
Using lambda expressions as function parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-19
C++ Stateless Lambda Expressions
Returning lambda expressions from functions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-20
C++ Stateless Lambda Expressions
Returning lambda expressions from functions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-21
C++ Stateless Lambda Expressions
Using lambda expressions as function parameters

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-22
C++ Stateless Lambda Expressions
Using lambda expressions as predicates

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateless Lambda Expressions S21-CPP-0080-23
C++ Stateful Lambda Expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-1
C++ Stateful Lambda Expressions
Compilation of stateless lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-2
C++ Stateful Lambda Expressions
Compilation of stateful lambda expressions

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-3
C++ Stateful Lambda Expressions
Capture by value

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-4
C++ Stateful Lambda Expressions
Using mutable to modify variables captured by value

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-5
C++ Stateful Lambda Expressions
Capture by reference

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-6
C++ Stateful Lambda Expressions
Capture by value and reference

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-7
C++ Stateful Lambda Expressions
Default captures

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-8
C++ Stateful Lambda Expressions
Using default and explicit captures

BEGINNING C++ PROGRAMMING LAMBDA EXPRESSIONS


Stateful Lambda Expressions S21-CPP-0120-9
Bonus Section Overview
Using Visual Studio Code with C++

Visual Studio Code – VS Code


• Microsoft • Fast
• Free • Small
• Cross-platform • Powerful
• Cross-language • Extensible

BEGINNING C++ PROGRAMMING BONUS SECTION - USING VISUAL STUDIO CODE


Section Overview VSCode-CPP-0010-1
Bonus Section Overview
Using Visual Studio Code with C++

•What we will do in this section


•Install VS Code
•Configure VS Code to work with C++
•Setup a folder structure that allows us to use multiple projects
•Build and run C++ projects
•Build and debug C++ projects
•How to use the source-code provided in the course

•We’ll do this for


•Windows
•Mac OSX
•Linux (Ubuntu 20.04 LTS)

BEGINNING C++ PROGRAMMING BONUS SECTION - USING VISUAL STUDIO CODE


Section Overview VSCode-CPP-0010-2
Bonus Section Overview
C++ Enumerations
• What is an enumeration?
• Motivation
• Structureof an enumeration
• Types of enumerations
• Unscoped enumeration
• Scoped enumeration

• Enumerations in use

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Section Overview Enums-CPP-0020-1
C++ Enumerations
What is an enumeration?

• A user-defined type that models a set of constant integral values

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-1
C++ Enumerations
What is an enumeration?

• A user-defined type that models a set of constant integral values

• The days of the week (Mon, Tue, Wed, . . .)


• The months of the year (Jan, Feb, Mar, . . .)
• The suits in a deck of cards (Clubs, Hearts, Spades, Diamonds)
• The values in a deck of cards (Ace, Two, Three, . . .)
• States of a system (Idle, Defense_Mode, Attack_Mode, . . .)
• The directions on a compass (North, South, East, West)

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-2
C++ Enumerations
Motivation
• Prior to enumerated types
• Unnamed numerical constants
• "Magic numbers"

• These constants would be used as conditionals in control statements


• Often, one would have no idea what an algorithm was doing

• As a result, many algorithms suffered from low readability and high numbers of
logic errors

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-3
Motivation
Readability

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-4
Motivation
Readability

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-5
Motivation
Algorithmic correctness

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-6
Motivation
Algorithmic correctness

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Motivation Enums-CPP-0040-7
C++ Enumerations
The Structure of an Enumeration

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-1
C++ Enumerations
The Structure of an Enumeration

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-2
C++ Enumerations
The Structure of an Enumeration

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-3
C++ Enumerations
The Structure of an Enumeration

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-4
C++ Enumerations
The Structure of an Enumeration

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-5
C++ Enumerations
Enumerator list

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-6
C++ Enumerations
Enumerator list

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-7
C++ Enumerations
Enumerator list

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-8
C++ Enumerations
Enumerator list

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-9
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-10
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-11
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-12
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-13
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-14
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-15
C++ Enumerations
Enumerator type

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-16
C++ Enumerations
Enumeration name

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-17
C++ Enumerations
Enumeration name

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-18
C++ Enumerations
Enumeration name

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


The Structure of an Enumeration Enums-CPP-0060-19
C++ Unscoped Enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-1
C++ Unscoped Enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-2
C++ Unscoped Enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-3
C++ Unscoped Enumerations
Using if and switch statements with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-4
C++ Unscoped Enumerations
Using if and switch statements with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-5
C++ Unscoped Enumerations
Using if and switch statements with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-6
C++ Unscoped Enumerations
Using if and switch statements with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-7
C++ Unscoped Enumerations
Using if and switch statements with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-8
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-9
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-10
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-11
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-12
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-13
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-14
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-15
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-16
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-17
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-18
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-19
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-20
C++ Unscoped Enumerations
Using cin and cout with unscoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Unscoped Enumerations Enums-CPP-0080-21
C++ Scoped Enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-1
C++ Scoped Enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-2
C++ Scoped Enumerations
Motivation

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-3
C++ Scoped Enumerations
Motivation

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-4
C++ Scoped Enumerations
Motivation

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-5
C++ Scoped Enumerations
Motivation

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-6
C++ Scoped Enumerations
Using if and switch statements with scoped enumerations

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-7
C++ Scoped Enumerations
Using scoped enumerator values

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-8
C++ Scoped Enumerations
Using scoped enumerator values

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-9
C++ Scoped Enumerations
Using scoped enumerator values

BEGINNING C++ PROGRAMMING BONUS SECTION - ENUMERATIONS


Scoped Enumerations Enums-CPP-0100-10

You might also like