Top Banner
Basics Machine, software, and program design and JWD © 2002 McGraw-Hill, Inc.
560

CPP Slides All

Nov 13, 2014

Download

Documents

ojay

C ++ Slides
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CPP Slides All

BasicsMachine, software, and program design

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 2: CPP Slides All

Computer OrganizationCPU - central processing unit

Memory

Input devices

Output devices

CPU - central processing unit Where decisions are made, computations are

performed, and input/output requests are delegatedMemory

Stores information being processed by the CPU

Input devices Allows people to supply information to computers

Output devices Allows people to receive information from computers

Page 3: CPP Slides All

Computer Organization

Memory

CPU

InputDevices

OutputDevices

Page 4: CPP Slides All

CPUBrains of the computer

Arithmetic calculations are performed using the Arithmetic/Logical Unit or ALU

Control unit decodes and executes instructionsArithmetic operations are performed using binary number system

Page 5: CPP Slides All

Control UnitThe fetch/execute cycle is the steps the CPU takes to execute an instructionPerforming the action specified by an instruction is known as executing the instructionThe program counter (PC) holds the memory address of the next instruction

Fetch the instruction towhich the PC points

Increment the PC

Execute the fetchedinstruction

Page 6: CPP Slides All

Input and Output DevicesAccessories that allow computer to perform specific tasks

Receive information for processing Return the results of processing Store information

Accessories that allow computer to perform specific tasks

Receive information for processing Return the results of processing Store information

Common input and output devices Speakers Mouse Scanner Printer Joystick CD-ROM Keyboard Microphone DVD

Accessories that allow computer to perform specific tasks

Receive information for processing Return the results of processing Store information

Common input and output devices Speakers Mouse Scanner Printer Joystick CD-ROM Keyboard Microphone DVD

Some devices are capable of both input and output Floppy drive Hard drive Magnetic tape

units

Page 7: CPP Slides All

MonitorDisplay device that operates like a television

Also known as CRT (cathode ray tube)Controlled by an output device called a graphics cardDisplayable area

Measured in dots per inch, dotsare often referred to aspixels (short for pictureelement)

Standard resolutionis 640 by 480

Many cards supportresolution of 1280 by1024 or better

Number of colors supported varies from 16 to billions

1280pixelsacrossscreen

1024pixelsdown

screen

Page 8: CPP Slides All

Application software Programs designed to perform specific tasks that are

transparent to the user

System software Programs that support the execution and

development of other programs Two major types

Operating systems Translation systems

Software

Page 9: CPP Slides All

Application SoftwareApplication software is the software that has made using computers indispensable and popular

Common application software Word processors Desktop publishing programs Spreadsheets Presentation managers Drawing programs

Application software is the software that has made using computers indispensable and popular

Common application software Word processors Desktop publishing programs Spreadsheets Presentation managers Drawing programs

Learning how to develop application software is our focus

Page 10: CPP Slides All

Examples Windows®, UNIX®, Mac OS X®

Controls and manages the computing resources

Important services that an operating system provides File system

Directories, folders, files Commands that allow for manipulation of the file system

Sort, delete, copy Ability to perform input and output on a variety of

devices Management of the running systems

Operating System

Page 11: CPP Slides All

Translation SystemSet of programs used to develop software

A key component of a translation system is a translator

Some types of translators Compiler

Converts from one language to another Linker

Combines resourcesExamples

Microsoft Visual C++®, CBuilder®, g++, Code Warrior®

Performs compilation, linking, and other activities.

Page 12: CPP Slides All

Software Development Activities

Editing

Compiling

Linking with precompiled files Object files Library modules

Loading and executing

Viewing the behavior of the program

Page 13: CPP Slides All

Software Development Cycle

Compile

Link

Library routines

Other object files

Think

Edit

Load

Execute

Source Program

Page 14: CPP Slides All

IDEsIntegrated Development Environments or IDEs

Supports the entire software development cycle E.g., MS Visual C++, Borland, Code Warrior

Provides all the capabilities for developing software Editor Compiler Linker Loader Debugger Viewer

Page 15: CPP Slides All

Engineering SoftwareSoftware engineering

Area of computer science concerned with building large software systems

Challenge Tremendous advances in hardware have not been

accompanied by comparable advances in software

Page 16: CPP Slides All

Complexity Trade-offSystem complexity tends to grow as the system becomes more user friendly

High

Low

Complexity

Total SoftwareComplexity

User Simplicity

Page 17: CPP Slides All

Software Engineering GoalsReliability

Understandability

Cost Effectiveness

Adaptability

Reusability

Reliability An unreliable life-critical system can be fatal

Understandability Future development is difficult if software is hard to

understandCost Effectiveness

Cost to develop and maintain should not exceed profitAdaptability

System that is adaptive is easier to alter and expandReusability

Improves reliability, maintainability, and profitability

Page 18: CPP Slides All

Abstraction Extract the relevant properties while ignoring

inessentials

Encapsulation Hide and protect essential information through a

controlled interfaceModularity

Hierarchy

Abstraction Extract the relevant properties while ignoring

inessentials

Encapsulation Hide and protect essential information through a

controlled interfaceModularity

Dividing an object into smaller modules so that it is easier to understand and manipulate

Hierarchy

Abstraction Extract the relevant properties while ignoring

inessentials

Encapsulation Hide and protect essential information through a

controlled interfaceModularity

Dividing an object into smaller modules so that it is easier to understand and manipulate

Hierarchy Ranking or ordering of objects based on some

relationship between them

Software Engineering Principles

Abstraction

Encapsulation

Modularity

Hierarchy

Abstraction Extract the relevant properties while ignoring

inessentials

Encapsulation

Modularity

Hierarchy

Page 19: CPP Slides All

Extract the relevant object properties while ignoring inessentials

Defines a view of the object

Example - car Car dealer views a car from selling features

standpoint Price, length of warranty, color, …

Mechanic views a car from systems maintenance standpoint Size of the oil filter, type of spark plugs, …

Abstraction

Price? Oil change?

Page 20: CPP Slides All

EncapsulationSteps

Decompose an object into parts Hide and protect essential information Supply interface that allows information to be modified in a

controlled and useful manner

Internal representation can be changed without affecting other system parts

Example - car radio Interface consists of controls

and power and antenna connectors The details of how it works is hidden

To install and use a radio Do not need to know anything about the radio’s electronics

Page 21: CPP Slides All

ModularityDividing an object into smaller pieces or modules so that the object is easier to understand and manipulate

Most complex systems are modular

Example - Automobile can be decomposed into subsystems

Cooling system Radiator ThermostatWater pump

Ignition system Battery Starter Spark plugs

Page 22: CPP Slides All

HierarchyHierarchy

Ranking or ordering of objects based on some relationship between them

Help us understand complex systems Example - a company hierarchy helps employees

understand the company and their positions within it

For complex systems, a useful way of ordering similar abstractions is a taxonomy from least general to most general

Page 23: CPP Slides All

Northern Timber Wolf Taxonomy

Kingdom Animalia Phylum Chordata Class Mammalia Order Carnivora Family Caninae Genus Canis Species Canis lupus Subspecies Canis lupus occidentalis Northern Timber Wolf

Page 24: CPP Slides All

OO Design and ProgrammingObject-oriented design and programming methodology supports good software engineering

Promotes thinking in a way that models the way we think and interact with the real world

Example - watching television The remote is a physical object with

properties Weight, size, can send message

to the television The television is also a physical object

with various properties

Page 25: CPP Slides All

ObjectsAn object is almost anything with the following characteristics

Name Properties The ability to act upon receiving a message

Basic message types Directive to perform an action Request to change one of its properties

Page 26: CPP Slides All

The individual digits of a binary number are referred to as bits Each bit represents a power of two

01011 = 0 • 24 + 1 • 23 + 0 • 22 + 1 • 21 + 1 • 20 = 11

00010 = 0 • 24 + 0 • 23 + 0 • 22 + 1 • 21 + 0 • 20 = 2

Binary Arithmetic

00010 + 01011 01101

Binaryaddition

2+ 11 13

Equivalentdecimaladdition

Page 27: CPP Slides All

Binary Arithmetic

5× 3 15

Equivalent decimal multiplication

0101 × 0011 0101 0101 0000 0000 0001111

Binary multiplication

Page 28: CPP Slides All

Two’s ComplementRepresentation for signed binary numbersLeading bit is a sign bit

Binary number with leading 0 is positive Binary number with leading 1 is negative

Magnitude of positive numbers is just the binary representationMagnitude of negative numbers is found by

Complement the bits Replace all the 1's with 0's, and all the 0's with 1's Add one to the complemented number

The carry in the most significant bit position is thrown away when performing arithmetic

Page 29: CPP Slides All

Two’s ComplementPerforming two's complement on the decimal 7 to get -7

Using a five-bit representation

7 = 00111 Convert to binary

11000 Complement the bits

11000 Add 1 to the complement + 00001 11001 Result is -7 in two's complement

Page 30: CPP Slides All

Two's Complement Arithmetic

Computing 8 - 7 using a two's complement representation with five-bit numbers

8 - 7 = 8 + (-7) = 1

01000 Two's complement of 8

11001 Two's complement of -7

01000 Add 8 and -7 + 11001 100001

00001 Is the five-bit result

Throw away the high-order

carry as we are using a five bit representation

Page 31: CPP Slides All

Fundamentals of C++Basic programming elements and concepts

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 32: CPP Slides All

Program statement Definition Declaration Action

Executable unit Named set of program statements Different languages refer to executable units by

different names Subroutine: Fortran and Basic Procedure: Pascal Function : C++

Program Organization

Page 33: CPP Slides All

Program OrganizationC++ program

Collection of definitions, declarations and functions Collection can span multiple files

Advantages Structured into small understandable units Complexity is reduced Overall program size decreases

Page 34: CPP Slides All

ObjectObject is a representation of some information

Name Values or properties

Data members Ability to react to requests (messages)!!

Member functionsWhen an object receives a message, one of two actions are performed

Object is directed to perform an action Object changes one of its properties

Page 35: CPP Slides All

// Program: Display greetings// Author(s): Ima Programmer// Date: 1/24/2001#include <iostream>#include <string>using namespace std;int main() { cout << "Hello world!" << endl; return 0;}

A First Program - Greeting.cppPreprocessor

directives

Insertionstatement

Ends executionsof main() which ends

program

Comments

Function

Function named main()

indicates start of

program

Provides simple access

Page 36: CPP Slides All

Greeting Output

Page 37: CPP Slides All

Definitions

Extraction

Definition with initialization

Area.cpp#include <iostream>using namespace std;int main() { // Extract length and width cout << "Rectangle dimensions: "; float Length; float Width; cin >> Length >> Width;

// Compute and insert the area

float Area = Length * Width;

cout << "Area = " << Area << " = Length " << Length << " * Width " << Width << endl; return 0;}

Page 38: CPP Slides All

Visual C++ IDE with Area.cpp

Page 39: CPP Slides All

Area.cpp Output

Page 40: CPP Slides All

CommentsAllow prose or commentary to be included in programImportance

Programs are read far more often than they are written Programs need to be understood so that they can be

maintainedC++ has two conventions for comments

// single line comment (preferred) /* long comment */ (save for debugging)

Typical uses Identify program and who wrote it Record when program was written Add descriptions of modifications

Page 41: CPP Slides All

Fundamental C++ ObjectsC++ has a large number of fundamental or built-in object typesThe fundamental object types fall into one of three categories

Integer objects Floating-point objects Character objects

11.28345

Z5

P 3.14

Page 42: CPP Slides All

Integer Object TypesThe basic integer object type is int

The size of an int depends on the machine and the compiler On PCs it is normally 16 or 32 bits

Other integers object types short: typically uses less bits long: typically uses more bits

Different types allow programmers to use resources more efficientlyStandard arithmetic and relational operations are available for these types

Page 43: CPP Slides All

Integer ConstantsInteger constants are positive or negative whole numbersInteger constant forms

Decimal Octal (base 8)

Digits 0, 1, 2, 3, 4, 5, 6, 7 Hexadecimal (base 16)

Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a , b, c, d, e, f, A, B, C, D, E, F

Consider 31 oct and 25 dec

Page 44: CPP Slides All

Decimal ConstantsExamples

97 40000L 50000 23a (illegal)

The type of the constant depends on its size, unless the type specifier is used

L or l indicates long integer

Page 45: CPP Slides All

Character Object TypesCharacter type char is related to the integer typesCharacters are encoded using a scheme where an integer represents a particular characterASCII is the dominant encoding scheme

Examples ' ' encoded as 32 '+' encoded as 43 'A' encoded as 65 'Z' encoded as 90 'a' encoded as 97 'z' encoded as 122

Appendix A gives the complete ASCII character set

Page 46: CPP Slides All

Character OperationsArithmetic and relational operations are defined for characters types

'a' < 'b' is true '4' > '3' is true '6' <= '2' is false

Page 47: CPP Slides All

Character ConstantsExplicit (literal) characters within single quotes

'a','D','*'

Special characters - delineated by a backslash \ Two character sequences (escape codes) Some important special escape codes

\t denotes a tab \n denotes a new line \\ denotes a backslash \' denotes a single quote \" denotes a double quote

'\t' is the explicit tab character, '\n' is the explicit new line character, and so on

Page 48: CPP Slides All

Literal String ConstantsA literal string constant is a sequence of zero or more characters enclosed in double quotes

"We are even loonier than you think" "Rust never sleeps\n" "Nilla is a Labrador Retriever"

Not a fundamental type

Page 49: CPP Slides All

Floating-Point Object Types Floating-point object types represent real numbers

Integer part Fractional part

The number 108.1517 breaks down into the following parts 108 - integer part 1517 - fractional part

C++ provides three floating-point object types float double long double

Page 50: CPP Slides All

Floating-Point ConstantsStandard decimal notation

134.1230.15F

Standard scientific notation1.45E6 0.979e-3L

When not specified, floating-point constants are of type double

F or f indicates single precision floating point value

L or l indicates long double floating point value

Page 51: CPP Slides All

NamesUsed to denote program values or components

A valid name is a sequence of Letters (upper and lowercase) Digits

A name cannot start with a digit Underscores

A name should not normally start with an underscore

Names are case sensitive MyObject is a different name than MYOBJECT

There are two kinds of names Keywords Identifiers

Page 52: CPP Slides All

KeywordsKeywords are words reserved as part of the language

int, return, float, double

They cannot be used by the programmer to name things

They consist of lowercase letters only

They have special meaning to the compiler

Page 53: CPP Slides All

IdentifiersIdentifiers should be

Short enough to be reasonable to type (single word is norm) Standard abbreviations are fine (but only standard

abbreviations) Long enough to be understandable

When using multiple word identifiers capitalize the first letter of each word

Examples Min Temperature CameraAngle CurrentNbrPoints

Page 54: CPP Slides All

DefinitionsAll objects that are used in a program must be defined

An object definition specifies Type Name

General definition form

Our convention is one definition per statement!

Type Id, Id, ..., Id;

Knowntype

List of one ormore identifiers

Page 55: CPP Slides All

Exampleschar Response;int MinElement;float Score;float Temperature;int i;int n;char c;float x;

Objects are uninitialized with this definition form

(Value of a object is whatever is in itsassigned memory location)

Page 56: CPP Slides All

Arithmetic OperatorsCommon

Addition + Subtraction - Multiplication * Division / Mod %

Note No exponentiation operator Single division operator Operators are overloaded to work with more than

one type of object

Write m*x + bnot mx + b

Page 57: CPP Slides All

Integer DivisionInteger division produces an integer result

Truncates the result

Examples 3 / 2 evaluates to 1 4 / 6 evaluates to 0 10 / 3 evaluates to 3

Page 58: CPP Slides All

ModProduces the remainder of the division

Examples 5 % 2 evaluates to 1 12 % 4 evaluates to 0 4 % 5 evaluates to 4

Page 59: CPP Slides All

Operators and PrecedenceConsider mx + bConsider m*x + b which of the following is it equivalent to

(m * x) + b m * (x + b)

Operator precedence tells how to evaluate expressionsStandard precedence order

() Evaluate first, if nested innermost

done first * / % Evaluate second. If there are

several,then evaluate from left-to-

right + - Evaluate third. If there are

several,then evaluate from left-to-

right

Page 60: CPP Slides All

Operator PrecedenceExamples

20 - 4 / 5 * 2 + 3 * 5 % 4

(4 / 5) ((4 / 5) * 2) ((4 / 5) * 2) (3 * 5) ((4 / 5) * 2) ((3 * 5) % 4)(20 -((4 / 5) * 2)) ((3 * 5) % 4)(20 -((4 / 5) * 2)) + ((3 * 5) % 4)

Page 61: CPP Slides All

Defining and InitializingWhen an object is defined using the basic form, the memory allotted to it contains random information

Better idea to specify its desired value at the same time Exception is when the next statement is an

extraction for the object

Remember our convention of one definition per statement!

Page 62: CPP Slides All

Examplesint FahrenheitFreezing = 32;char FinalGrade = 'A';cout << "Slope of line: ";float m;cin >> m;cout << "Intercept: ";float b;cin >> b;cout << "X value of interest: ";float x;cin >> x;float y = (m * x) + b;

Page 63: CPP Slides All

Modifying ObjectsOperators and Expressions

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 64: CPP Slides All

Memory Depictionfloat y = 12.5;

12.5y1001100210031004

Page 65: CPP Slides All

Memory Depictionfloat y = 12.5;int Temperature = 32;

12.5

32

y

Temperature

100110021003100410051006

Page 66: CPP Slides All

Memory Depictionfloat y = 12.5;int Temperature = 32;char Letter = 'c';

12.5

32'c'

y

TemperatureLetter

1001100210031004100510061007

Page 67: CPP Slides All

Memory Depictionfloat y = 12.5;int Temperature = 32;char Letter = 'c';int Number;

12.5

32'c'

y

TemperatureLetter

1001100210031004100510061007

-Number 10081009

Page 68: CPP Slides All

Assignment StatementBasic form

object = expression ;Celsius = (Fahrenheit - 32) * 5 / 9;y = m * x + b;

Action Expression is evaluated Expression value stored in object

Target becomes source

Page 69: CPP Slides All

Definitionint NewStudents = 6; 6NewStudents

Page 70: CPP Slides All

Definitionint NewStudents = 6;int OldStudents = 21;

6

21

NewStudents

OldStudents

Page 71: CPP Slides All

Definitionint NewStudents = 6;int OldStudents = 21;int TotalStudents;

6

21

NewStudents

OldStudents

-TotalStudents

Page 72: CPP Slides All

Assignment Statementint NewStudents = 6;int OldStudents = 21;int TotalStudents;

TotalStudents = NewStudents + OldStudents;

6

21

NewStudents

OldStudents

?TotalStudents

Page 73: CPP Slides All

Assignment Statementint NewStudents = 6;int OldStudents = 21;int TotalStudents;

TotalStudents = NewStudents + OldStudents;

6

21

NewStudents

OldStudents

27TotalStudents

Page 74: CPP Slides All

Assignment Statementint NewStudents = 6;int OldStudents = 21;int TotalStudents;

TotalStudents = NewStudents + OldStudents;

OldStudents = TotalStudents;

6

?

NewStudents

OldStudents

27TotalStudents

Page 75: CPP Slides All

Assignment Statementint NewStudents = 6;int OldStudents = 21;int TotalStudents;

TotalStudents = NewStudents + OldStudents;

OldStudents = TotalStudents;

6

27

NewStudents

OldStudents

27TotalStudents

Page 76: CPP Slides All

Considerint Value1 = 10; 10Value1

Page 77: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;

10

20

Value1

Value2

Page 78: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;int Hold = Value1;

10

20

Value1

Value2

10Hold

Page 79: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;int Hold = Value1;

Value1 = Value2;

?

20

Value1

Value2

10Hold

Page 80: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;int Hold = Value1;

Value1 = Value2;

20

20

Value1

Value2

10Hold

Page 81: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;int Hold = Value1;

Value1 = Value2;

Value2 = Hold;

20

?

Value1

Value2

10Hold

Page 82: CPP Slides All

Considerint Value1 = 10;int Value2 = 20;int Hold = Value1;

Value1 = Value2;

Value2 = Hold;

We swapped the values of objects Value1 and Value2 using Hold as temporary holder for Value1’s starting value!

20

10

Value1

Value2

10Hold

Page 83: CPP Slides All

Incrementingint i = 1; i 1

Page 84: CPP Slides All

Incrementingint i = 1;

i = i + 1;

Assign the value of expression i + 1 to i

Evaluates to 2

i 1

2i

Page 85: CPP Slides All

Const DefinitionsModifier const indicates that an object cannot be changed

Object is read-only

Useful when defining objects representing physical and mathematical constants

const float Pi = 3.1415;

Value has a name that can be used throughout the program

const int SampleSize = 100;

Makes changing the constant easy Only need to change the definition and recompile

Page 86: CPP Slides All

Assignment ConversionsFloating-point expression assigned to an integer object is truncated

Integer expression assigned to a floating-point object is converted to a floating-point value

Considerfloat y = 2.7;int i = 15;int j = 10;i = y; // i is now 2cout << i << endl; y = j; // y is now 10.0cout << y << endl;

Page 87: CPP Slides All

Nonfundamental TypesNonfundamental as they are additions to the languageC++ permits definition of new types and classes

A class is a special kind of typeClass objects typically have

Data members that represent attributes and values Member functions for object inspection and

manipulation Members are accessed using the selection operator

(.)j = s.size();

Auxiliary functions for other behaviorsLibraries often provide special-purpose types and classesProgrammers can also define their own types and classes

Page 88: CPP Slides All

ExamplesStandard Template Library (STL) provides class string

EzWindows library provides several graphical types and classes

SimpleWindow is a class for creating and manipulating window objects

RectangleShape is a class for creating and manipulating rectangle objects

Page 89: CPP Slides All

Class stringClass string

Used to represent a sequence of characters as a single object

Some definitionsstring Name = "Joanne";string DecimalPoint = ".";string empty = "";string copy = name;string Question = '?'; // illegal

Page 90: CPP Slides All

Nonfundamental TypesTo access a library use a preprocessor directive to add its definitions to your program file

#include <string>The using statement makes syntax less clumsy

Without itstd::string s = "Sharp";std::string t = "Spiffy";

With itusing namespace std; // std contains stringstring s = "Sharp";string t = "Spiffy";

Page 91: CPP Slides All

EzWindows Library ObjectsDefinitions are the same form as other objectsExample

SimpleWindow W;

Most non-fundamental classes have been created so that an object is automatically initialized to a sensible value

SimpleWindow objects have member functions to process messages to manipulate the objects

Most important member function is Open() which causes the object to be displayed on the screen Example

W.Open();

Page 92: CPP Slides All

InitializationClass objects may have several attributes to initialize

Syntax for initializing an object with multiple attributesType Identifier(Exp1, Exp2, ..., Expn);

SimpleWindow object has several optional attributes

SimpleWindow W("Window Fun", 8, 4); First attribute

Window banner Second attribute

Width of window in centimeters Third attribute

Height of window in centimeters

Page 93: CPP Slides All

An EzWindows Program#include <iostream>using namespace std;#include "ezwin.h"int ApiMain() {

SimpleWindow W("A Window", 12, 12);W.Open();

cout << "Enter a character to exit" << endl;char a;cin >> a;

return 0;}

Page 94: CPP Slides All

An EzWindows Project File

Page 95: CPP Slides All

An EzWindows Project File

Page 96: CPP Slides All

Sample Display Behavior

Page 97: CPP Slides All

RectangleShape ObjectsEzWindows also provides RectangleShape for manipulating rectangles

RectangleShape objects can specify the following attributes SimpleWindow object that contains the rectangle (mandatory) Offset from left edge of the SimpleWindow Offset from top edge of the SimpleWindow

Offsets are measured in centimeters from rectangle center Width in centimeters Height in centimeters Color

color is an EzWindows type

Page 98: CPP Slides All

RectangleShape ObjectsExamplesSimpleWindow W1("My Window", 20, 20);SimpleWindow W2("My Other Window", 15, 10);

RectangleShape R(W1, 4, 2, Blue, 3, 2);RectangleShape S(W2, 5, 2, Red, 1, 1);RectangleShape T(W1, 3, 1, Black, 4, 5);RectangleShape U(W1, 4, 9);

Page 99: CPP Slides All

RectangleShape ObjectsSome RectangleShape member functions for processing messages

Draw() Causes rectangle to be displayed in its associated

window GetWidth()

Returns width of object in centimeters GetHeight()

Returns height of object in centimeters SetSize()

Takes two attributes -- a width and height -- that are used to reset dimensions of the rectangle

Page 100: CPP Slides All

Another EzWindows Program#include <iostream>using namespace std;#include "rect.h"int ApiMain() {

SimpleWindow W("Rectangular Fun", 12, 12);W.Open();RectangleShape R(W, 5.0, 2.5, Blue, 1, 2);R.Draw();cout << "Enter a character to exit" << endl;char Response;cin >> Response;return 0;

}

Page 101: CPP Slides All

Sample Display Behavior

Page 102: CPP Slides All

Compound AssignmentC++ has a large set of operators for applying an operation to an object and then storing the result back into the object

Examplesint i = 3;i += 4; // i is now 7cout << i << endl;

float a = 3.2;a *= 2.0; // a is now 6.4cout << a << endl;

Page 103: CPP Slides All

Increment and DecrementC++ has special operators for incrementing or decrementing an object by oneExamplesint k = 4;++k; // k is 5k++; // k is 6cout << k << endl;int i = k++; // i is 6, k is 7cout << i << " " << k << endl;int j = ++k; // j is 8, k is 8cout << j << " " << k << endl;

Page 104: CPP Slides All

Class stringSome string member functions

size() determines number of characters in the stringstring Saying = "Rambling with Gambling";cout << Saying.size() << endl; // 22

substr() determines a substring (Note first position has index 0)string Word = Saying.substr(9, 4); // with

find() computes the position of a subsequenceint j = Saying.find("it"); // 10int k = Saying.find("its"); // ?

Page 105: CPP Slides All

Class stringAuxiliary functions and operators

getline() extracts the next input linestring Response;cout << "Enter text: ";getline(cin, Response, '\n');cout << "Response is \"" << Response << "\"” << endl;

Example runEnter text: Want what you doResponse is "Want what you do"

Page 106: CPP Slides All

Class stringAuxiliary operators

+ string concatenationstring Part1 = "Me";string Part2 = " and ";string Part3 = "You";string All = Part1 + Part2 + Part3;

+= compound concatenation assignmentstring ThePlace = "Brooklyn";ThePlace += ", NY";

Page 107: CPP Slides All

#include <iostream>using namespace std;int main() { cout << "Enter the date in American format: " << "(e.g., January 1, 2001) : "; string Date; getline(cin, Date, '\n'); int i = Date.find(" "); string Month = Date.substr(0, i); int k = Date.find(","); string Day = Date.substr(i + 1, k - i - 1); string Year = Date.substr(k + 2, Date.size() - 1); string NewDate = Day + " " + Month + " " + Year; cout << "Original date: " << Date << endl; cout << "Converted date: " << NewDate << endl; return 0;}

Page 108: CPP Slides All
Page 109: CPP Slides All

If Control ConstructA mechanism for deciding whether an action should be taken

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 110: CPP Slides All

Boolean AlgebraLogical expressions have the one of two values - true or false

A rectangle has three sides The instructor has a pleasant smile

The branch of mathematics is called Boolean algebra Developed by the British mathematician George Boole

in the 19th centuryThree key logical operators

And Or Not

Page 111: CPP Slides All

Boolean AlgebraTruth tables

Lists all combinations of operand values and the result of the operation for each combination

ExampleP Q P and Q

False False FalseFalse True FalseTrue False FalseTrue True True

Page 112: CPP Slides All

Boolean AlgebraOr truth table

P Q P or Q

False False FalseFalse True TrueTrue False TrueTrue True True

Page 113: CPP Slides All

Boolean AlgebraNot truth table

P not P

False TrueTrue False

Page 114: CPP Slides All

Boolean AlgebraCan create complex logical expressions by combining simple logical expressionsExample

not (P and Q)A truth table can be used to determine when a logical expression is true

P Q P and Q not (P and Q)

False False False TrueFalse True False TrueTrue False False TrueTrue True True False

Page 115: CPP Slides All

A Boolean TypeC++ contains a type named boolType bool has two symbolic constants

true false

Boolean operators The and operator is && The or operator is || The not operator is !

Warning & and | are also operators so be careful what you

type

Page 116: CPP Slides All

A Boolean TypeExample logical expressions

bool P = true;bool Q = false;bool R = true;bool S = (P && Q);bool T = ((!Q) || R);bool U = !(R && (!Q));

Page 117: CPP Slides All

Relational OperatorsEquality operators

== !=

Examples int i = 32; int k = 45; bool q = (i == k); bool r = (i != k);

Page 118: CPP Slides All

Relational OperatorsOrdering operators

< > >= <=

Examples int i = 5; int k = 12; bool p = (i < 10); bool q = (k > i); bool r = (i >= k); bool s = (k <= 12);

Page 119: CPP Slides All

Operator Precedence Revisited

Precedence of operators (from highest to lowest) Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment

Page 120: CPP Slides All

Operator Precedence Revisited

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

Page 121: CPP Slides All

Operator Precedence Revisited

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

Yuck! Do not write expressions like this!

Page 122: CPP Slides All

Operator Precedence Revisited

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to ((((5 *15) + 4) == 13) && (12 < 19))

||((!false) == (5 < 24))

Consider5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

However, for your information it is equivalent to

Page 123: CPP Slides All

Conditional ConstructsProvide

Ability to control whether a statement list is executed

Two constructs If statement

if if-else if-else-ef

Switch statement Left for reading

Page 124: CPP Slides All

The Basic If StatementSyntax

if (Expression) Action

If the Expression is true then execute Action

Action is either a single statement or a group of statements within braces

Expression

Action

true false

Page 125: CPP Slides All

Exampleif (Value < 0) { Value = -Value;}

Value < 0

Value = -Value

true false

Is our number negative?

If Value is not lessthan zero then ournumber is fine as is

If Value is less thanzero then we need toupdate its value tothat of its additive

inverse

Our number isnow definitelynonnegative

Page 126: CPP Slides All

Sorting Two Numberscout << "Enter two integers: ";int Value1;int Value2;cin >> Value1 >> Value2;if (Value1 > Value2) {

int RememberValue1 = Value1;Value1 = Value2;Value2 = RememberValue1;

}cout << "The input in sorted order: " << Value1 << " " << Value2 << endl;

Page 127: CPP Slides All

Semanticsvalue2 < value1

int rememberValue1 = value1 value1 = value2 value2 = rememberValue1

true false

Are the numbersout of order

Rearrange value1and value2 to

put their valuesin the proper

order

The numbers wereinitially in order

The numbers wererearranged into the

proper order

The numbers are inorder

Page 128: CPP Slides All

What is the Output?int m = 5;int n = 10;

if (m < n) ++m;++n;

cout << " m = " << m << " n = " n << endl;

Page 129: CPP Slides All

The If-Else StatementSyntaxif (Expression)

Action1else Action2

If Expression is true then executeAction1 otherwise execute Action2

if (v == 0) { cout << "v is 0"; }

else { cout << "v is not 0"; }

Expression

Action1 Action2

true false

Page 130: CPP Slides All

Finding the Maxcout << "Enter two integers: ";int Value1;int Value2;cin >> Value1 >> Value2;int Max;if (Value1 < Value2) {

Max = Value2;}else {

Max = Value1;}cout << "Maximum of inputs is: " << Max << endl;

Page 131: CPP Slides All

Finding the Max

Value1 < Value2

Max = Value2 Max = Value1

true false

Is Value2 larger than Value1

Yes, it is . So Value2 islarger than Value1. Inthis case, Max is set

to Value2No, its not. So Value1is at least as large asValue2. In this case,Max is set to Value1

Either case, Max is setcorrectly

Page 132: CPP Slides All

SelectionIt is often the case that depending upon the value of an expression we want to perform a particular actionTwo major ways of accomplishing this choice

if-else-if statement if-else statements “glued” together

Switch statement An advanced construct

Page 133: CPP Slides All

An If-Else-If Statementif ( nbr < 0 ){

cout << nbr << " is negative" << endl;}else if ( nbr > 0 ) {

cout << nbr << " is positive" << endl;}else {

cout << nbr << " is zero" << endl;}

Page 134: CPP Slides All

A Switch Statementswitch (ch) {

case 'a': case 'A':case 'e': case 'E':case 'i': case 'I':case 'o': case 'O':case 'u': case 'U':

cout << ch << " is a vowel" << endl;break;

default:cout << ch << " is not a vowel" << endl;

}

Page 135: CPP Slides All

cout << "Enter simple expression: ";int Left;int Right;char Operator;cin >> Left >> Operator >> Right;cout << Left << " " << Operator << " " << Right << " = ";switch (Operator) {

case '+' : cout << Left + Right << endl; break;case '-' : cout << Left - Right << endl; break;case '*' : cout << Left * Right << endl; break;case '/' : cout << Left / Right << endl; break;default: cout << "Illegal operation" << endl;

}

Page 136: CPP Slides All
Page 137: CPP Slides All

Iterative ConstructsMechanisms for deciding under what conditions an action should be repeated

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 138: CPP Slides All

Averaging

Page 139: CPP Slides All

Determining Average Magnitude

Suppose we want to calculate the average apparent brightness of a list of five star magnitude values

Can we do it? Yes, it would be easy

Suppose we want to calculate the average apparent brightness of a list of five star magnitude values

Can we do it Yes, it would be easy

Suppose we want to calculate the average apparent brightness of a list of 8,479 stars visible from earth

Can we do it Yes, but it would be gruesome without the use of

iteration

Page 140: CPP Slides All

C++ Iterative ConstructsThree constructs

while statement for statement do-while statement

Page 141: CPP Slides All

While Syntax

Logical expression that determineswhether the action is to be executed

while ( Expression ) Action

Action to be iterativelyperformed until logical

expression is false

Page 142: CPP Slides All

While Semantics

Expression

Action

true false

Expression isevaluated at the

start of eachiteration of the

loop

If Expression istrue, Action is

executed If Expression isfalse, program

executioncontinues withnext statement

Page 143: CPP Slides All

Computing an Averageint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

Page 144: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

Suppose input contains: 1 5 3 1 6

listSize 4

Page 145: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

Suppose input contains: 1 5 3 1 6

4listSize

0

Page 146: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

Suppose input contains: 1 5 3 1 6

4listSize

00

Page 147: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

Suppose input contains: 1 5 3 1 6

4listSize

00

Page 148: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

00--

Page 149: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

001

Page 150: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

0011

Page 151: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

011

1

Page 152: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

111

Page 153: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

11--

Page 154: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

115

Page 155: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

1156

Page 156: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

165

2

Page 157: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

2656

Page 158: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

26--

2

Page 159: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

263

2

Page 160: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

2639

Page 161: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

293

3

Page 162: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

393

3

Page 163: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

39--

3

Page 164: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

391

3

Page 165: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

391

10

Page 166: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

3101

4

Page 167: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

value

Suppose input contains: 1 5 3 1 6

4listSize

3101

4

Page 168: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

Suppose input contains: 1 5 3 1 6

4listSize

310

average 2.5

4

Page 169: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

numberProcessed

sum

average

Suppose input contains: 1 5 3 1 6

4listSize

3102.5

4

Page 170: CPP Slides All

Execution Traceint listSize = 4;int numberProcessed = 0;double sum = 0;while (numberProcessed < listSize) {

double value;cin >> value;sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

Suppose input contains: 1 5 3 1 6

Stays in stream until extracted

Page 171: CPP Slides All

Power of Two Tableconst int TableSize = 20;

int i = 0;long Entry = 1;

cout << "i" << "\t\t" << "2 ** i" << endl;

while (i < TableSize) {cout << i << "\t\t" << Entry << endl;Entry = 2 * Entry;++i;

}

Page 172: CPP Slides All

Better Way of Averagingint numberProcessed = 0;double sum = 0;double value;while ( cin >> value ) {

sum += value;++numberProcessed;

}double average = sum / numberProcessed ;cout << "Average: " << average << endl;

What if list is empty?

The value of the input operation corresponds to true only if a successful

extraction was made

Page 173: CPP Slides All

Even Better Way of Averaging

int numberProcessed = 0;double sum = 0;double value;while ( cin >> value ) {

sum += value;++numberProcessed;

}if ( numberProcessed > 0 ) {

double average = sum / numberProcessed ;cout << "Average: " << average << endl;

}else {

cout << "No list to average" << endl;}

Page 174: CPP Slides All

The For StatementSyntax

for (ForInit ; ForExpression; PostExpression) Action

Examplefor (int i = 0; i < 3; ++i) { cout << "i is " << i << endl;}

Page 175: CPP Slides All

ForExpr

Action

true false

ForInit

PostExpr

Evaluated onceat the beginning

of the forstatements's

execution The ForExpr isevaluated at thestart of each

iteration of theloop

If ForExpr istrue, Action is

executed

After the Actionhas completed,

thePostExpression

is evaluated

If ForExpr isfalse, program

executioncontinues withnext statement

After evaluating thePostExpression, the next

iteration of the loop starts

Page 176: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i 0

Page 177: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i 0

Page 178: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0

i 0

Page 179: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0

i 0

Page 180: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0

i 1

Page 181: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i 1

Page 182: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1

i 1

Page 183: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1

i 1

Page 184: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1

i 2

Page 185: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1

i 2

Page 186: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1i is 2

i 2

Page 187: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1i is 2

i 2

Page 188: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1i is 2

i 3

Page 189: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1i is 2

i 3

Page 190: CPP Slides All

Execution Tracefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;}cout << "all done" << endl;

i is 0i is 1i is 2all done

i 3

Page 191: CPP Slides All

Table Revisitingconst int TableSize = 20;

long Entry = 1;

cout << "i" << "\t\t" << "2**i" << endl;

for (int i = 0; i <= TableSize; ++i) {cout << i << "\t\t" << Entry << endl;Entry *= 2;

}

Page 192: CPP Slides All

Table Revisitingconst int TableSize = 20;

long Entry = 1;

cout << "i" << "\t\t" << "2**i" << endl;

for (int i = 0; i < TableSize; ++i) {cout << i << "\t\t" << Entry << endl;Entry = 2 * Entry;

}

cout << "i is" << i << endl; // illegal

The scope of i is limited to the loop!

Page 193: CPP Slides All

Displaying a DiagonalSimpleWindow W("One diagonal", 5.5, 2.25);W.Open();for (int j = 1; j <= 3; ++j) {

float x = j * 0.75 + 0.25;float y = j * 0.75 - 0.25;float Side = 0.4;RectangleShape S(W, x, y, Blue, Side, Side);S.Draw();

}

Page 194: CPP Slides All

Sample Display

Page 195: CPP Slides All

Displaying Three DiagonalsSimpleWindow W("Three diagonals", 6.5, 2.25);W.Open();for (int i = 1; i <= 3; ++i) {

for (int j = 1; j <= 3; ++j) {float x = i - 1 + j * 0.75 + 0.25;float y = j * 0.75 - 0.25;float Side = 0.4;RectangleShape S(W, x, y, Blue, Side, Side);S.Draw();

}} The scope of i includes the inner loop.

The scope of j is just the inner loop.

Page 196: CPP Slides All

Sample Display

Page 197: CPP Slides All

int Counter1 = 0;int Counter2 = 0;int Counter3 = 0;int Counter4 = 0;int Counter5 = 0;

++Counter1;for (int i = 1; i <= 10; ++i) {

++Counter2;

for (int j = 1; j <= 20; ++j) { ++Counter3; }++Counter4;}++Counter5;cout << Counter1 << " " << Counter2 << " "

<< Counter3 << " " << Counter4 << " " << Counter5 << endl;

Page 198: CPP Slides All

For Into WhileObservation

The for statement is equivalent to{ForInit;while (ForExpression) {

Action;PostExpression;

}}

Page 199: CPP Slides All

Counting Charactersint NumberOfNonBlanks = 0;int NumberOfUpperCase = 0;char c;while (cin >> c) {

++NumberOfNonBlanks;if ((c >= 'A') && (c <= 'Z')) {

++NumberOfUpperCase;}

}cout << "Nonblank characters: " << NumberOfNonBlanks << endl << "Uppercase characters: " << NumberOfUpperCase << endl;

Only extracts nonblank characters

Page 200: CPP Slides All

Counting All Characterschar c;int NumberOfCharacters = 0;int NumberOfLines = 0;while ( cin.get(c) ) {

++NumberOfCharacters;if (c == '\n') {

++NumberOfLines}

}cout << "Characters: " << NumberOfCharacters << endl << "Lines: " << NumberOfLines << endl;

Extracts all characters

Page 201: CPP Slides All

#include <iostream>#include <fstream>using namespace std;int main() {

ifstream fin("mydata.txt");int ValuesProcessed = 0;float ValueSum = 0;float Value;while ( fin >> Value ) {ValueSum += Value;++ValuesProcessed;}if (ValuesProcessed > 0) {ofstream fout("average.txt");float Average = ValueSum / ValuesProcessed;fout << "Average: " << Average << endl;return 0;}else {cerr << "No list to average" << endl;return 1;}

}

File Processing

Page 202: CPP Slides All

Iteration Do’sKey Points

Make sure there is a statement that will eventually terminate the iteration criterion The loop must stop!

Make sure that initialization of loop counters or iterators is properly performed

Have a clear purpose for the loop Document the purpose of the loop Document how the body of the loop advances the

purpose of the loop

Page 203: CPP Slides All

The Do-While StatementSyntaxdo Action while (Expression)Semantics

Execute Action If Expression is true

then execute Action again

Repeat this process until Expression evaluates to false

Action is either a single statement or a group of statements within braces

Action

true

false

Expression

Page 204: CPP Slides All

Waiting for a Proper Replychar Reply;do { cout << "Decision (y, n): "; if (cin >> Reply) Reply = tolower(Reply); else Reply = 'n';} while ((Reply != 'y') && (Reply != 'n'));

Page 205: CPP Slides All

LibrariesComputational assistants

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 206: CPP Slides All

Previous examples Programmer-defined functions

main() ApiMain()

Library-defined functions cin.get() string member functions size() RectangleShape member function Draw() SimpleWindow member function Open()

Advice Don’t reinvent the wheel! There are lots of libraries out

there

Functions

Page 207: CPP Slides All

TerminologyA function is invoked by a function call / function invocation

y = f(a);

Page 208: CPP Slides All

TerminologyA function call specifies

The function name The name indicates what function is to be called

y = f(a);

A function call specifies The function name

The name indicates what function is to be called

y = f(a);

The actual parameters to be used in the invocation The values are the information that the called

function requires from the invoking function to do its task

y = f(a);

Page 209: CPP Slides All

TerminologyA function call produces a return value

The return value is the value of the function call

y = f(a);

Page 210: CPP Slides All

Invocation ProcessFlow of control is temporarily transferred to the invoked function

Correspondence established between actual parameters of the invocation with the formal parameters of the definition

cout << "Enter number: ";double a;cin >> a;y = f(a);cout << y;

Value of a is given to x

double f(double x) {

double result =

x*x + 2*x + 5;

return result;

}

Page 211: CPP Slides All

Invocation ProcessFlow of control is temporarily transferred to the invoked function

Local objects are also maintained in the invocation’s activation record. Even main() has a record

cout << "Enter number: ";double a;cin >> a;y = f(a);cout << y;

Activation record is largeenough to store valuesassociated with each objectthat is defined by the function

double f(double x) {

double result =

x*x + 2*x + 5;

return result;

}

Page 212: CPP Slides All

Invocation ProcessFlow of control is temporarily transferred to the invoked function

Other information may also be maintained in the invocation’s activation record

cout << "Enter number: ";double a;cin >> a;y = f(a);cout << y;

Possibly a pointer to thecurrent statement beingexecuted and a pointer tothe invoking statement

double f(double x) {

double result =

x*x + 2*x + 5;

return result;

}

Page 213: CPP Slides All

Invocation ProcessFlow of control is temporarily transferred to the invoked function

Next statement executed is the first one in the invoked function

cout << "Enter number: ";double a;cin >> a;y = f(a);cout << y;

double f(double x) {

double result =

x*x + 2*x + 5;

return result;

}

Page 214: CPP Slides All

Invocation ProcessFlow of control is temporarily transferred to the invoked function

After function completes its action, flow of control is returned to the invoking function and the return value is used as value of invocation

cout << "Enter number: ";double a;cin >> a;y = f(a);cout << y;

double f(double x) {

double result =

x*x + 2*x + 5;

return result;

}

Page 215: CPP Slides All

Execution ProcessFunction body of invoked function is executed

Flow of control then returns to the invocation statement

The return value of the invoked function is used as the value of the invocation expression

Page 216: CPP Slides All

Function PrototypesBefore a function can appear in an invocation its interface must be specified

Prototype or complete definition

int Max(int a, int b)

Type of value thatthe function returns

FunctionType FunctionName ( ParameterList )

A description of the form theparameters (if any) are to take

Identifier name offunction

Page 217: CPP Slides All

Function PrototypesBefore a function can appear in an invocation its interface must be specified

Prototypes are normally kept in library header files

int Max(int a, int b)

Type of value thatthe function returns

FunctionType FunctionName ( ParameterList )

A description of the form theparameters (if any) are to take

Identifier name offunction

Page 218: CPP Slides All

LibrariesLibrary

Collection of functions, classes, and objects grouped by commonality of purpose

Include statement provides access to the names and descriptions of the library components

Linker connects program to actual library definitions

Previous examples String: STL’s string class Graphics: EzWindows

Page 219: CPP Slides All

Basic Translation Process

Processpreprocessordirectives to

produce atranslation

unit

Executable Unit

Source program

Checktranslation

unit for legalsyntax and

compile it intoan object file

Link object filewith standard

object filesand other

object files toproduce anexecutable

unit

Page 220: CPP Slides All

Some Standard Librariesfstream

File stream processingassert

C-based library for assertion processingiomanip

Formatted input/output (I/O) requestsctype

C-based library for character manipulationsmath

C-based library for trigonometric and logarithmic functions

Note C++ has many other libraries

Page 221: CPP Slides All

Library Header FilesDescribes library components

Typically contains Function prototypes

Interface description Class definitions

Sometimes contains Object definitions

Example: cout and cin in iostream

Page 222: CPP Slides All

Library Header FilesTypically do not contain function definitions

Definitions are in source files Access to compiled versions of source files provided

by a linker

Page 223: CPP Slides All

#include <iostream>#include <cmath>using namespace std;int main() {

cout << "Enter Quadratic coefficients: ";double a, b, c;cin >> a >> b >> c;if ( (a != 0) && (b*b - 4*a*c > 0) ) {double radical = sqrt(b*b - 4*a*c);double root1 = (-b + radical) / (2*a);double root2 = (-b - radical) / (2*a);cout << "Roots: " << root1 << " " << root2; }else {cout << "Does not have two real roots";}return 0;

}

Invocation

Library header files

Page 224: CPP Slides All

#include <iostream>#include <fstream> // file stream libraryusing namespace std;int main() {

ifstream fin("mydata.txt");int ValuesProcessed = 0;float ValueSum = 0;float Value;while (fin >> Value) {

ValueSum += Value;++ValuesProcessed;

}if (ValuesProcessed > 0) {

ofstream fout("average.txt");float Average = ValueSum / ValuesProcessed;fout << "Average: " << Average << endl;return 0;

}else {

cerr << "No list to average" << endl;return 1;

}}

Page 225: CPP Slides All

ifstream sin("in1.txt"); // extract from in1.txtofstream sout("out1.txt"); // insert to out1.txt

string s;while (sin >> s) {

sout << s << endl;}sin.close(); // done with in1.txtsout.close(); // done with out1.txt

sin.open("in2.txt"); // now extract from in2.txtsout.open("out.txt", // now append to out2.txt(ios_base::out | ios_base::app));

while (sin >> s) {sout << s << endl;

}

sin.close(); // done with in2.txtsout.close(); // done with out2.txt

Page 226: CPP Slides All
Page 227: CPP Slides All

Programmer-defined FunctionsDevelopment of simple functions using value and reference parameters

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 228: CPP Slides All

Includes description of the interface and the function body

Interface Similar to a function prototype, but parameters’

names are required Body

Statement list with curly braces that comprises its actions

Return statement to indicate value of invocation

Function Definition

Page 229: CPP Slides All

float CircleArea (float r) {const float Pi = 3.1415;return Pi * r * r;

}

Function Definition

Function bodyReturn statement

Local object definition

Formal parameterReturn type Function name

Page 230: CPP Slides All

Function Invocation

cout << CircleArea(MyRadius) << endl;

To process the invocation, the function that contains the insertion statement is suspended and CircleArea() does its job. The insertion statement is then completed using the value

supplied by CircleArea().

Actual parameter

Page 231: CPP Slides All

Simple ProgramsSingle file

Include statements Using statements Function prototypes Function definitions

Single file Include statements Using statements Function prototypes Function definitions

Functions use value parameter passing Also known as pass by value or call by value

The actual parameter is evaluated and a copy is given to the invoked function

Page 232: CPP Slides All

#include <iostream>using namespace std;float CircleArea(float r);// main(): manage circle computationint main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0;}// CircleArea(): compute area of radius r circlefloat CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r;}

Page 233: CPP Slides All

Value Parameter RulesFormal parameter is created on function invocation and it is initialized with the value of the actual parameter

Changes to formal parameter do not affect actual parameter

Reference to a formal parameter produces the value for it in the current activation record

New activation record for every function invocation

Formal parameter name is only known within its function

Formal parameter ceases to exist when the function completes

Activation record memory is automatically released at function completion

Page 234: CPP Slides All

Returnvalue

FunctionInput streamdata

Output streamdata

Information to functioncan come from

parameters or an inputstream

Parameters

Information fromfunction can comethrough a return

value or an outputstream

Page 235: CPP Slides All

PromptAndRead()// PromptAndRead(): prompt and extract next// integer

int PromptAndRead() {cout << "Enter number (integer): ";int Response;cin >> Response;

return Response;}

Page 236: CPP Slides All

Sum()// Sum(): compute sum of integers in a ... bint Sum(int a, int b) {

int Total = 0;for (int i = a; i <= b; ++i) {

Total += i;}return Total;

}

Page 237: CPP Slides All

ProblemDefinition

Input two numbers that represent a range of integers and display the sum of the integers that lie in that range

Design Prompt user and read the first number Prompt user and read the second number Calculate the sum of integers in the range

smaller...larger by adding in turn each integer in that range

Display the sum

Page 238: CPP Slides All

Range.cpp#include <iostream>using namespace std;

int PromptAndRead();int Sum(int a, int b);

int main() {int FirstNumber = PromptAndRead();int SecondNumber = PromptAndRead();int RangeSum = Sum(FirstNumber , SecondNumber);cout << "The sum from " << FirstNumber << " to " << SecondNumber << " is " << RangeSum << endl;return 0;

}

Page 239: CPP Slides All

Range.cpp// PromptAndRead(): prompt & extract next integerint PromptAndRead() {

cout << "Enter number (integer): ";int Response;cin >> Response;return Response;

}

// Sum(): compute sum of integers in a ... bint Sum(int a, int b) {

int Total = 0;for (int i = a; i <= b; ++i) {

Total += i;}return Total;

}

Page 240: CPP Slides All

A block is a list of statements within curly bracesBlocks can be put anywhere a statement can be putBlocks within blocks are nested blocksAn object name is known only within the block in which it is defined and in nested blocks of that blockA parameter can be considered to be defined at the beginning of the block corresponding to the function body

Blocks and Local ScopeA block is a list of statements within curly braces

Page 241: CPP Slides All

Local Object Manipulationvoid f() { int i = 1; cout << i << endl; // insert 1 { int j = 10;

cout << i << j << endl; // insert 1 10 i = 2; cout << i << j << endl // insert 2 10 } cout << i << endl; // insert 2 cout << j << endl; // illegal}

Page 242: CPP Slides All

Name ReuseIf a nested block defines an object with the same name as enclosing block, the new definition is in effect in the nested block

Page 243: CPP Slides All

However, Don’t Do This At Home

void f() { { int i = 1; cout << i << endl; // insert 1 { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a } cout << i << endl; // insert 1 } cout << i << endl; // illegal insert}

Page 244: CPP Slides All

Global ScopeObjects not defined within a block are global objects

A global object can be used by any function in the file that is defined after the global object

It is best to avoid programmer-defined global objects Exceptions tend to be important constants

Global objects with appropriate declarations can even be used in other program files

cout, cin, and cerr are global objects that are defined in by the iostream library

Local objects can reuse a global object's name Unary scope operator :: can provide access to global

object even if name reuse has occurred

Page 245: CPP Slides All

Don’t Do This At Home Eitherint i = 1;int main() { cout << i << endl; // insert 1 {

char i = 'a'; cout << i << endl; // insert a ::i = 2; cout << i << endl; // insert a cout << ::i << endl; // insert 2

}cout << i << endl;

return 0;}

Page 246: CPP Slides All

Considerint main() {

int Number1 = PromptAndRead();int Number2 = PromptAndRead();if (Number1 > Number2) {

Swap(Number1, Number2);}cout << "The numbers in sorted order:" << Number1 << ", " << Number2 << endl;return 0;

}

Page 247: CPP Slides All

Usingvoid Swap(int a, int b) {

int Temp = a;a = b;b = Temp;return;

}

Page 248: CPP Slides All

Doesn’t do what we want!

Page 249: CPP Slides All

ConsiderA parameter passing style where

Changes to the formal parameter change the actual parameter

Page 250: CPP Slides All

That would work!

Page 251: CPP Slides All

Reference ParametersIf the formal argument declaration is a reference parameter then

Formal parameter becomes an alias for the actual parameter Changes to the formal parameter change the

actual parameterFunction definition determines whether a parameter’s passing style is by value or by reference Reference parameter form

ptypei &pnamei

void Swap(int &a, int &b)

Page 252: CPP Slides All

Reconsiderint main() {

int Number1 = PromptAndRead();int Number2 = PromptAndRead();if (Number1 > Number2) {

Swap(Number1, Number2); }

cout << "The numbers in sorted order: " << Number1 << ", " << Number2 << endl;return 0;

}

Page 253: CPP Slides All

Usingvoid Swap(int &a, int &b) {

int Temp = a;a = b;b = Temp;return;

}

Return statement notnecessary for void functions

Passed by reference -- in aninvocation the actual

parameter is given ratherthan a copy

Page 254: CPP Slides All

Considerint i = 5;int j = 6;Swap(i, j);int a = 7;int b = 8;Swap(b, a);

void Swap(int &a, int &b) {int Temp = a;a = b;b = Temp;return;

}

Page 255: CPP Slides All

ExtractionFunction to extract a value from a given stream

void GetNumber(int &MyNumber, istream &sin) {sin >> MyNumber;return;

}

Why is the stream a reference parameter?

Why is MyNumber a reference parameter?

Page 256: CPP Slides All

Getnum.cppint main() {

ifstream fin("mydata.txt");int Number1;int Number2;cout << "Enter number: ";GetNumber(Number1, cin);// not needed: cout << "Enter number: ";GetNumber(Number2, fin);if (Number1 > Number2) {Swap(Number1, Number2);

}cout << "The numbers in sorted order: " << Number1 << ", " << Number2 << endl;return 0;

}

Page 257: CPP Slides All

Constant ParametersThe const modifier can be applied to formal parameter declarations

const indicates that the function may not modify the parameter void PromptAndGet(int &n, const string &s) {

cout << s ; cin >> n ; // s = "Got it"; // illegal assignment

} // caught by compiler

Sample invocationint x;PromptAndGet(x, "Enter number (n): ");

Page 258: CPP Slides All

Constant ParametersUsefulness

When we want to pass an object by reference, but we do not want to let the called function modify the object

Usefulness When we want to pass an object by reference, but

we do not want to let the called function modify the object

Question Why not just pass the object by value?

Answer ?

Usefulness When we want to pass an object by reference, but

we do not want to let the called function modify the object

Question Why not just pass the object by value?

Answer For large objects, making a copy of the object can be

very inefficient

Page 259: CPP Slides All

Passing Constant Rectanglesvoid DrawBoxes(const RectangleShape &R1, const RectangleShape &R2) {

R1.Draw();R2.Draw();

}

int ApiMain() {SimpleWindow Demo("Demo Program");Demo.Open();RectangleShape Rect1(Demo, 3, 2, Blue);RectangleShape Rect2(Demo, 6, 5, Yellow);DrawBoxes(Rect1, Rect2);return 0;

}

Page 260: CPP Slides All

Default ParametersObservations

Our functions up to this point required that we explicitly pass a value for each of the function parameters

Observations Our functions up to this point required that we

explicitly pass a value for each of the function parameters

It would be convenient to define functions that accept a varying number of parameters

Observations Our functions up to this point required that we

explicitly pass a value for each of the function parameters

It would be convenient to define functions that accept a varying number of parameters

Default parameters Allows programmer to define a default behavior

A value for a parameter can be implicitly passed Reduces need for similar functions that differ only

in the number of parameters accepted

Page 261: CPP Slides All

Default ParametersIf the formal argument declaration is of the form

ptypei pnamei = dvaluei

then If there is no ith argument in the function invocation, pnamei is initialized to dvaluei

The parameter pnamei is an optional value parameter

Optional reference parameters are also permitted

Page 262: CPP Slides All

Considervoid PrintChar(char c = '=', int n = 80) {

for (int i = 0; i < n; ++i)cout << c;

}

What happens in the following invocations?PrintChar('*', 20);PrintChar('-');PrintChar();

Page 263: CPP Slides All

Default ParametersDefault parameters must appear after any mandatory parameters

Bad examplevoid Trouble(int x = 5, double z, double y) {...

}

Cannot come before mandatory parameters

Page 264: CPP Slides All

Default ParametersConsiderbool GetNumber(int &n, istream &sin = cin) {return sin >> n ;

}Some possible invocationsint x, y, z;ifstream fin("Data.txt");GetNumber(x, cin);GetNumber(y);GetNumber(z, fin);

Design your functions for ease and reuse!

Page 265: CPP Slides All

Function OverloadingA function name can be overloaded

Two functions with the same name but with different interfaces Typically this means different formal parameter

lists Difference in number of parameters

Min(a, b, c)Min(a, b)

Difference in types of parametersMin(10, 20)Min(4.4, 9.2)

Page 266: CPP Slides All

Function Overloadingint Min(int a, int b) {

cout << "Using int min()" << endl;if (a > b)

return b;else

return a;}double Min(double a, double b) {

cout << "Using double min()" << endl;if (a > b)

return b;else

return a;}

Page 267: CPP Slides All

Function Overloadingint main() {

int a = 10;int b = 20;double x = 4.4;double y = 9.2;int c = Min(a, b);cout << "c is " << c << endl;int z = Min(x, y);cout << "z is " << z << endl;return 0;

}

Page 268: CPP Slides All

Function OverloadingCompiler uses function overload resolution to call the most appropriate function

First looks for a function definition where the formal and actual parameters exactly match

If there is no exact match, the compiler will attempt to cast the actual parameters to ones used by an appropriate function

The rules for function definition overloading are very complicated

Advice Be very careful when using this feature

Page 269: CPP Slides All

Random NumbersGenerating a sequence of random numbers is often useful

In a game, it ensures that a player does not seethe same behavior each time

In a simulation of a complex system,random numbers can be used tohelp generate random events Car crash in a simulation

of a highway system Likelihood of a gene in cell mutation Weather simulation

Page 270: CPP Slides All

Uniform Random NumbersUniform random number sequence

A sequence of random numbers where Each value in the sequence is drawn from the

same range of numbers In each position of the sequence, any value in the

number range is equally likely to occur

Page 271: CPP Slides All

Random NumbersExamples

Generate a uniform randomnumber sequence in the range1 to 6 Use a fair six-sided die Each roll represents a new random number

Generate a uniform random numbersequence in the range 1 to 2 Use a fair coin

Heads: 1, Tails: 2

Page 272: CPP Slides All

Random NumbersWe can write an algorithmfor generating what lookslike random numbers

Because it’s an algorithm,we know the rules for generating the next number

The generated numbers are not really random They are properly called pseudorandom numbers

30 21 9 28 29 ...

Page 273: CPP Slides All

Stdlib LibraryProvides in part functions for generating pseudorandom numbers

rand() Returns a uniform pseudorandom unsigned int

from the inclusive interval 0 to RAND_MAX#include <iostream>#include <string>#include <cstdlib>using namespace std;int main() { for (int i = 1; i <= 5; ++i)

cout << rand() << endl; return 0;

}

Page 274: CPP Slides All

Different SequencesTo produce a different sequence, invoke

void srand(unsigned int);

Consider seed.cppint main() { cout << "Enter a seed: "; unsigned int Seed; cin >> Seed; srand(Seed); for (int i = 1; i <= 5; ++i) cout << rand() << endl; return 0;

}

Page 275: CPP Slides All

Different SequencesTo automatically get a different sequence each time

Need a method of setting the seed to a random value The standard method is to use the computer's

clock as the value of the seed The function invocation time() can be used

Returns an integral value of type time_t Invocation time(0) returns a suitable value

for generating a random sequence

Page 276: CPP Slides All

Randseed.cpp#include <iostream>#include <string>#include <cstdlib>#include <ctime>using namespace std;

int main() { srand((unsigned int) time(0)); for (int i = 1; i <= 5; ++i)

cout << rand() << endl; return 0;

}

Page 277: CPP Slides All

Class ConstructDefining objects with attributes and behavior

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 278: CPP Slides All

Class TypesClass construct

Allows programmers to define new data types for representing information

Class type objects can have both attribute components and behavior components

Provides the object-oriented programming in C++

Class construct Allows programmers to define new data types for

representing information

Class type objects can have both attribute components and behavior components

Provides the object-oriented programming in C++

Example we shall consider is RectangleShape

Page 279: CPP Slides All

TerminologyClient

Program using a class

Object behaviors Realized in C++ via member functions (methods)

Object attributes Are known as data members in C++

Client Program using a class

Object behaviors Realized in C++ via member functions (methods)

RectangleShapes can be drawn or resized

Object attributes Are known as data members in C++

Client Program using a class

Object behaviors Realized in C++ via member functions (methods)

RectangleShapes can be drawn or resized

Object attributes Are known as data members in C++

RectangleShapes have width, height, position, color

Page 280: CPP Slides All

Member FunctionsProvide a controlled interface to data members and object access and manipulation

Create objects of the class Inspect, mutate, and manipulate object of the class Can be used to keep data members in a correct state

SetSize() SetColor() Draw()

Page 281: CPP Slides All

Member FunctionsConstructors

Member functions that initialize an object during its definitionRectangleShape R(W, x, y, c, w, h);

Factoid Constructors do not have a type

Considered superfluous

Page 282: CPP Slides All

Member FunctionsInspectors

Member functions that act as a messenger that returns the value of an attribute

Example RectangleShapes have an inspector GetColor()

color CurrColor = R.GetColor();

Page 283: CPP Slides All

Member FunctionsMutators

Changes the value of an attribute

Example RectangleShapes have a mutator SetColor()

R.SetColor(Black);

Page 284: CPP Slides All

Member FunctionsFacilitators

Causes an object to perform some action or service

Example RectangleShapes have a facilitator Draw()

R.Draw();

Page 285: CPP Slides All

A Simple RectangleShape Class

Consider a simpler version of the RectangleShape than what is defined in rect.h

Giving the class definition not the implementation

The definition in rect.h uses inheritance and member functions with default parameters

If you are wondering what is missing Default constructor parameters Member function

Erase() Inherited member functions

HasBorder(), SetBorder(), and ClearBorder()

Page 286: CPP Slides All

#ifndef RECT_SHAPE_H#define RECT_SHAPE_H#include "ezwin.h"class RectangleShape {

public: // constructor RectangleShape(SimpleWindow &Window, float XCoord, float YCoord, const color &c, float Width, float Height); // facilitator void Draw();

Simple RectangleShape

Header File

Passed by reference, do not want a copy of the window

ezwin.h get us definitions of SimpleWindow and color

Accessright

indicates no

limitations on who can use these

members

Preprocessor directives

Page 287: CPP Slides All

// inspectors color GetColor() const; float GetWidth() const; float GetHeight() const; void GetSize(float &Width, float &Height)

const; void GetPosition(float &XCoord, float &YCoord) const; SimpleWindow& GetWindow() const;

Simple RectangleShape

Reference return, brings actual window (not a copy)

Indicates the member functions won’t change the object

Page 288: CPP Slides All

// mutators void SetColor(const color &c); void SetPosition(float XCoord, float YCoord); void SetSize(float Width, float Height);

Simple RectangleShapeLack of const indicate the member function might change the object

Page 289: CPP Slides All

private: // data members SimpleWindow &Window; float thisXCenter; float thisYCenter; color thisColor; float thisWidth; float thisHeight;

};

#endif

Simple RectangleShapeA client cannot directly access either private or protected data members

Access right

Close of #ifndef directive

Page 290: CPP Slides All

Access TestsConsiderSimpleWindow W("Testing", 20, 10);RectangleShape R(W, 2, 2, Blue, 4, 3);const RectangleShape S(W, 15, 10, Red, 5, 6);

Can we do the following? color c = R.GetColor(); color d = S.GetColor(); color d = R.thisColor; R.DetColor(Yellow); S.SetColor(Black);

Page 291: CPP Slides All

The RectangleShape ClassPublic access

All clients and class membershave access to the publicmembers

Private access Only class

membershave accessto theprivatemembers

Public datamembers and

member functions

Private datamembers and

member functions

Access fromoutside of class

Accessdenied

Page 292: CPP Slides All

O: R1DM: Window: &W,Color: Cyan,

XCenter: 1, YCenter: 4Width: 3, Height: 3

Instantiations

C: RectangleShape DM: Window, Color,XCenter, YCenter,Width, Height

MF: Draw(), GetColor(), GetSize(),GetWidth(), GetHeight(), GetPosition(),

GetWindow(), SetColor(),SetPosition(),SetSize()

O: R2DM: Window: &W,

Color: Red,XCenter: 6, YCenter: 4Width: 1, Height: 2

Page 293: CPP Slides All

#include "rect.h”SimpleWindow ColorWindow("Color Palette", 8.0, 8.0);int ApiMain() {

const int SideSize = 1;float XPosition = 1.5;const float YPosition = 4;ColorWindow.Open();RectangleShape ColorPatch(ColorWindow, XPosition, YPosition, White, SideSize, SideSize);for (int c = Red; c <= Magenta; c = color(c + 1)) {

ColorPatch.SetColor(color(c));ColorPatch.SetPosition(XPosition, YPosition);ColorPatch.Draw();XPosition += SideSize;

}return 0;

}

Page 294: CPP Slides All
Page 295: CPP Slides All

Abstract Data Types

Development and Implementation

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 296: CPP Slides All

Our GoalWell-defined representations that allow objects to be created and used in an intuitive manner

User should not have to bother with unnecessary details

Example programming a microwave to make popcorn should

not require a physics course

Page 297: CPP Slides All

Golden RuleUse information hiding and encapsulation to support integrity of data

Put implementation details in a separate module Implementation details complicate the class

declarations

Data members are private so that use of the interface is required Makes clients generally immune to

implementation changes

Page 298: CPP Slides All

Another Golden RuleKeep it simple – class minimality rule

Implement a behavior as a nonmember function when possible

Only add a behavior if it is necessary

Page 299: CPP Slides All

Abstract Data TypeWell-defined and complete data abstraction using the information-hiding principle

Page 300: CPP Slides All

Rational Number ReviewRational number

Ratio of two integers: a/b Numerator over the denominator

Standard operations Addition Multiplication

Subtraction Division

bdbc+ad=d

c+ba

bdac=d

c*ba

ab

-cd

=ad - bc

bd bcad=d

c/ba

Page 301: CPP Slides All

Abstract Data TypeConsiderRational a(1,2); // a = 1/2Rational b(2,3); // b = 2/3cout << a << " + " << b << " = " << a + b;Rational s; // s = 0/1Rational t; // t = 0/1cin >> s >> t;cout << s << " * " << t << " = " << s * t;

Observation Natural look that is analogous to fundamental-type

arithmetic objects

Page 302: CPP Slides All

Rational AttributesA numerator and denominator

Implies in part a class representation with two private int data members NumeratorValue and DenominatorValue

Page 303: CPP Slides All

Rational Public BehaviorsRational arithmetic

Addition, subtraction, multiplication, and division

Rational relational Equality and less than comparisons

Practice rule of class minimality

Page 304: CPP Slides All

Rational Public BehaviorsConstruction

Default construction Design decision 0/1

Specific construction Allow client to specify numerator and denominator

Copy construction Provided automatically

Assignment Provided automatically

Insertion and extraction

Page 305: CPP Slides All

Non-Public BehaviorsInspection and mutation of data members

Clients deal with a Rational object!

Page 306: CPP Slides All

Auxiliary BehaviorsOperations (necessarily public)

Arithmetic, relational, insertion, and extraction operations Provides the natural form we expect

Class definition provides a functional form that auxiliary operators use

Provides commutativity consistency For C++ reasons 1 + r and r + 1 would not

be treated the same if addition was a member operation

Page 307: CPP Slides All

Object aAttributes:

NumeratorValue(1)DenominatorValue(2)

Object bAttributes:

NumeratorValue(2)DenominatorValue(3)

Class RationalPublic interface: Add(), Subtract(),

Multiply(),Divide(), Equal(),LessThan(), Insert(),Extract()Data members: NumeratorValue,

DenominatorValueOther members: GetNumerator(), GetDenominator(),

SetNumerator(), SetDenominator(),

InstantiationRational a(1,2);

InstantiationRational b(2,3);

Page 308: CPP Slides All

Library ComponentsRational.h

Class definitions and library function prototypesRational.cpp

Implementation source code – member and auxiliary function definitions Auxiliary functions are assisting global functions

that provide expected but non-member capabilities

Rational.obj Translated version of Rational.cpp (linkable)

Rational.lib Library version of Rational.obj that is more readily

linkable

Page 309: CPP Slides All

#include <iostream>using namespace std;#include "rational.h"int main() {

Rational r;Rational s;cout << "Enter two rationals(a/b): ";cin >> r >> s;Rational Sum = r + s;cout << r << " + " << s << " = " << Sum;return 0;

}

MyProgram.cppMaking use of the Rationalclass. The header file providesaccess to the class definitionand to auxiliary functionprototypes. The header filedoes not provide member andauxiliary definitions

Page 310: CPP Slides All

Compiler translates the unit and produces MyProgram.objCompiler recognizes that MyProgram.obj does not contain actual definitions of Rational constructor, +, >>, and <<Linker is used to combine definitions from the Rational library file with MyProgram.obj to produce MyProgram.exe

Compiler must be told where to find the Rational library file

Producing MyProgram.exePreprocessor combines the definitions and prototypes in iostream and rational headers along with MyProgram.cpp to produce a compilation unit

Compiler must be told where to look for Rational.h

Page 311: CPP Slides All

Producing MyProgram.exe

Processpreprocessordirectives toproduce atranslation

unit

MyProgram.exe

MyProgram.cpp

Checktranslation unitfor legal syntaxand compile itinto object file

MyProgram.obj

Link object filewith standard

library filesand rationallibrary file to

produceexecutable

unit

Page 312: CPP Slides All

Rational Header File Overview

File layout Class definition and library prototypes nested within

preprocessor statements Ensures one inclusion per translation unit

Class definition precedes library prototypes#ifndef RATIONAL_H#define RATIONAL_Hclass Rational {

// …} ;

// library prototypes …#endif

Page 313: CPP Slides All

Class Rational Overviewclass Rational { // from rational.h

public:// for everybody including clients

protected:// for Rational member functions and for// member functions from classes derived// from rational

private:// for Rational member functions

} ;

Page 314: CPP Slides All

Rational Public Sectionpublic:

// default constructorRational();// specific constructorRational(int numer, int denom = 1);// arithmetic facilitatorsRational Add(const Rational &r) const;Rational Multiply(const Rational &r) const;// stream facilitatorsvoid Insert(ostream &sout) const;void Extract(istream &sin);

Page 315: CPP Slides All

Rational Protected Sectionprotected:

// inspectorsint GetNumerator() const;int GetDenominator() const;// mutatorsvoid SetNumerator(int numer);void SetDenominator(int denom);

Page 316: CPP Slides All

Rational Private Sectionprivate:

// data membersint NumeratorValue;int DenominatorValue;

Page 317: CPP Slides All

// after the class definition in rational.h

Rational operator+(const Rational &r, const Rational &s);

Rational operator*(const Rational &r, const Rational &s);

ostream& operator<<(ostream &sout, const Rational &s);

istream& operator>>(istream &sin, Rational &r);

Auxiliary Operator Prototypes

Page 318: CPP Slides All

Auxiliary Operator Importance

Rational r;Rational s;r.Extract(cin);s.Extract(cin);Rational t = r.Add(s);t.Insert(cout);

Rational r;Rational s;cin >> r;cin >> s;Rational t = r + s;cout << t;

Natural lookShould << be a member?

Considerr << cout;

Page 319: CPP Slides All

Const Powerconst Rational OneHalf(1,2);cout << OneHalf; // legalcin >> OneHalf; // illegal

Page 320: CPP Slides All

Rational Implementation#include <iostream> // Start of rational.cpp#include <string>using namespace std;#include "rational.h"

// default constructorRational::Rational() {

SetNumerator(0);SetDenominator(1);

}

ExampleRational r; // r = 0/1

Which objects arebeing referenced?

Is this necessary?

Page 321: CPP Slides All

RememberEvery class object

Has its own data members

Has its own member functions When a member function accesses a data

member By default the function accesses the data

member of the object to which it belongs!

No special notation needed

Page 322: CPP Slides All

RememberAuxiliary functions

Are not class members

To access a public member of an object, an auxiliary function must use the dot operator on the desired object

object.member

Page 323: CPP Slides All

Specific Constructor// (numer, denom) constructorRational::Rational(int numer, int denom) {

SetNumerator(numer); SetDenominator(denom);

}

ExampleRational t(2,3); // t = 2/3

Rational u(2); // u = 2/1 (why?)

Page 324: CPP Slides All

Inspectorsint Rational::GetNumerator() const {

return NumeratorValue;}

int Rational::GetDenominator() const {return DenominatorValue;

}

Where are the following legal?int a = GetNumerator();int b = t.GetNumerator();

Which object isbeing referenced?

Why the const?

Page 325: CPP Slides All

Numerator Mutatorvoid Rational::SetNumerator(int numer) {

NumeratorValue = numer;}

Where are the following legal?

SetNumerator(1);

t.SetNumerator(2);

Why no const?

Page 326: CPP Slides All

Denominator Mutatorvoid Rational::SetDenominator(int denom) {

if (denom != 0) {DenominatorValue = denom;

}else {

cerr << "Illegal denominator: " << denom << "using 1" << endl;DenominatorValue = 1;

}}

ExampleSetDenominator(5);

Page 327: CPP Slides All

Addition FacilitatorRational Rational::Add(const Rational &r) const {

int a = GetNumerator();int b = GetDenominator();int c = r.GetNumerator();int d = r.GetDenominator();return Rational(a*d + b*c, b*d);

}

Examplecout << t.Add(u);

Page 328: CPP Slides All

Multiplication FacilitatorRational Rational::Multiply(const Rational &r) const {

int a = GetNumerator();int b = GetDenominator();int c = r.GetNumerator();int d = r.GetDenominator();return Rational(a*c, b*d);

}

Examplet.Multiply(u);

Page 329: CPP Slides All

Insertion Facilitatorvoid Rational::Insert(ostream &sout) const {

sout << GetNumerator() << '/' << GetDenominator();return;

}

Examplet.Insert(cout);

Why is sout a reference parameter?

Page 330: CPP Slides All

Basic Extraction Facilitatorvoid Rational::Extract(istream &sin) {

int numer;int denom;char slash;sin >> numer >> slash >> denom;assert(slash == '/');SetNumerator(numer);SetDenominator(denom);return;

}

Examplet.Extract(cin);

Page 331: CPP Slides All

Auxiliary Arithmetic Operators

Rational operator+( const Rational &r, const Rational &s) {

return r.Add(s);}

Rational operator*( const Rational &r, const Rational &s) {

return r.Multiply(s);}

Examplecout << (t + t) * t;

Page 332: CPP Slides All

Auxiliary Insertion Operatorostream& operator<<( ostream &sout, const Rational &r) {

r.Insert(sout);return sout;

}

Why a reference return?

Note we can do either

t.Insert(cout); cout << endl; // unnaturalcout << t << endl; // natural

Page 333: CPP Slides All

Auxiliary Extraction Operator// extracting a Rationalistream& operator>>(istream &sin, Rational &r) {

r.Extract(sin);return sin;

}

Why a reference return?

We can do either

t.Extract(cin); // unnaturalcin >> t; // natural

Page 334: CPP Slides All

What’s Happening Here?Suppose the following definitions are in effect

Rational a(2,3);Rational b(3,4);Rational c(1,2);

Why do the following statements workRational s(a);Rational t = b;c = a

C++ has automatically provided us a copy constructor and an assignment operator

Page 335: CPP Slides All

Copy ConstructionDefault copy construction

Copy of one object to another in a bit-wise manner The representation of the source is copied to the

target in a bit-by-bit manner

This type of copy is called shallow copying

Class developers are free to implement their own copy constructor

Rational does need a special one, but we will define one for the experience

Page 336: CPP Slides All

A Rational Copy ConstructorRational::Rational(const Rational &r) {

int a = r.GetNumerator();int b = r.GetDenomiator();

SetNumerator(a);SetDenominator(b);

}

Rational s(a);Rational t = b;

Page 337: CPP Slides All

Gang Of ThreeIf it is appropriate to define a copy constructor then

Consider also defining Assignment operator

Copy source to target and return target A = B = C

Destructor Clean up the object when it goes out of scope

We give the name Gang of three to the Copy constructor, assignment operator, and the

destructor

Page 338: CPP Slides All

A Rational Assignment OperatorRational& Rational::operator =(const Rational &r) {

int a = r.GetNumerator();int b = r.GetDenomiator();

SetNumerator(a);SetDenominator(b);

return *this; }

a = b;a = b = c;

*this is C++ syntax for the object whose member function was invoked

Page 339: CPP Slides All

Rational DestructorRational::~Rational() {

// nothing to do}

Page 340: CPP Slides All
Page 341: CPP Slides All

ArraysA Mechanism for representing lists

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 342: CPP Slides All

ListsProblem solving often requires information be viewed as a list

List may be one-dimensional or multidimensional

Problem solving often requires information be viewed as a list

List may be one-dimensional or multidimensionalC++ provides two list mechanisms

Arrays Traditional and important because of legacy

libraries Restrictions on its use

Problem solving often requires information be viewed as a list

List may be one-dimensional or multidimensionalC++ provides two list mechanisms

Arrays Traditional and important because of legacy

libraries Restrictions on its use

Container classes First-class list representation Common containers provided by STL

Vector, queue, stack, map, … Preferred long-term programming practice

Page 343: CPP Slides All

ListsAnalogies

Egg carton Apartments Cassette carrier

Page 344: CPP Slides All

Array TerminologyList is composed of elementsList is composed of elementsElements in a list have a common name

The list as a whole is referenced through the common name

List is composed of elementsElements in a list have a common name

The list as a whole is referenced through the common name

List elements are of the same type — the base type

List is composed of elementsElements in a list have a common name

The list as a whole is referenced through the common name

List elements are of the same type — the base typeElements of a list are referenced by subscripting or indexing the common name

Page 345: CPP Slides All

Subscripts are denoted as expressions within brackets: [ ]Base type can be any fundamental, library-defined, or programmer-defined typeThe index type is integer and the index range must be0 ... n-1

where n is a programmer-defined constant expression.

Parameter passing style Always call by reference (no indication necessary)

C++ RestrictionsSubscripts are denoted as expressions within brackets: [ ]Subscripts are denoted as expressions within brackets: [ ]Base type can be any fundamental, library-defined, or programmer-defined type

Subscripts are denoted as expressions within brackets: [ ]Base type can be any fundamental, library-defined, or programmer-defined typeThe index type is integer and the index range must be0 ... n-1

where n is a programmer-defined constant expression.

Page 346: CPP Slides All

Basic Array Definition

Type ofvalues in

list

BaseType Id [ SizeExp ] ;

Nameof list

Bracketed constantexpression

indicating numberof elements in list

double X [ 100 ] ;

// Subscripts are 0 through 99

Page 347: CPP Slides All

Example DefinitionsSupposeconst int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;

Supposeconst int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;

Then the following are all correct array definitionsint A[10]; // array of 10 intschar B[MaxStringSize]; // array of 80 charsdouble C[M*N]; // array of 800 floatsint Values[MaxListSize]; // array of 1000 intsRational D[N-15]; // array of 5 Rationals

Page 348: CPP Slides All

SubscriptingSupposeint A[10]; // array of 10 ints A[0], … A[9]

To access individual element must apply a subscript to list name A

A subscript is a bracketed expression also known as the index

Supposeint A[10]; // array of 10 ints A[0], … A[9]

To access individual element must apply a subscript to list name A

A subscript is a bracketed expression also known as the index

First element of list has index 0A[0]

Supposeint A[10]; // array of 10 ints A[0], … A[9]

To access individual element must apply a subscript to list name A

A subscript is a bracketed expression also known as the index

First element of list has index 0A[0]

Second element of list has index 1, and so onA[1]

Supposeint A[10]; // array of 10 ints A[0], … A[9]

To access individual element must apply a subscript to list name A

A subscript is a bracketed expression also known as the index

First element of list has index 0A[0]

Second element of list has index 1, and so onA[1]

Last element has an index one less than the size of the list

A[9]

Supposeint A[10]; // array of 10 ints A[0], … A[9]

To access individual element must apply a subscript to list name A

A subscript is a bracketed expression also known as the index

First element of list has index 0A[0]

Second element of list has index 1, and so onA[1]

Last element has an index one less than the size of the list

A[9] Incorrect indexing is a common error

A[10] // does not exist

Page 349: CPP Slides All

Array ElementsSupposeint A[10]; // array of 10 uninitialized ints

To access an individual element we must apply a subscript to list name A

-- -- ----AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 350: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- -- ----AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 351: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- -- --1AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 352: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- -- --1AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 5-- -- --

Page 353: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- 8 --1AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 5-- -- --

Page 354: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 5-- -- --

Page 355: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 5-- 12 --

Page 356: CPP Slides All

Array Element ManipulationConsiderint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 53 12 --

Page 357: CPP Slides All

Extracting Values For A List int A[MaxListSize];int n = 0;int CurrentInput;while((n < MaxListSize) && (cin >> CurrentInput)){

A[n] = CurrentInput;++n;

}

Page 358: CPP Slides All

Displaying A List// List A of n elements has already been setfor (int i = 0; i < n; ++i) {

cout << A[i] << " ";}cout << endl;

Page 359: CPP Slides All

Smallest ValueProblem

Find the smallest value in a list of integersInput

A list of integers and a value indicating the number of integers

Output Smallest value in the list

Note List remains unchanged after finding the smallest

value!

Page 360: CPP Slides All

Preliminary DesignRealizations

When looking for value with distinguishing characteristics, need a way of remembering best candidate found so far Make it a function -- likely to be used often

Realizations When looking for value with distinguishing

characteristics, need a way of remembering best candidate found so far Make it a function -- likely to be used often

Design Search array looking for smallest value

Use a loop to consider each element in turn If current element is smallest so far, then update

smallest value so far candidate When done examining all of the elements, the

smallest value seen so far is the smallest value

Page 361: CPP Slides All

Necessary InformationInformation to be maintained

Array with values to be inspected for smallest value Number of values in array Index of current element being considered Smallest value so far

Page 362: CPP Slides All

A More Detailed DesignSolution

Function that takes array of values and array size as its two in parameters; returns smallest value seen as its value

Initialize smallest value so far to first element For each of the other elements in the array in turn

If it is smaller than the smallest value so far, update the value of the smallest value so far to be the current element

Return smallest value seen as value of function

Page 363: CPP Slides All

int ListMinimum(const int A[], int asize) {assert(asize >= 1);int SmallestValueSoFar = A[0]; for (int i = 1; i < asize; ++i) {

if (A[i] < SmallestValueSoFar ) {SmallestValueSoFar = A[i];

}}return SmallestValueSoFar ;

}

Passing An ArrayNotice brackets are empty

Could we just assign a 0 and have it work?

Page 364: CPP Slides All

Using ListMinimum()What happens with the following?

int Number[6];Number[0] = 3; Number[1] = 88; Number[2] = -7;Number[3] = 9; Number[4] = 1; Number[5] = 24;

cout << ListMinimum(Number, 6) << endl;

int List[3];List[0] = 9; List[1] = 12; List[2] = 45;

cout << ListMinimum(List, 3) << endl;

Notice no brackets

Page 365: CPP Slides All

RememberArrays are always passed by reference

Artifact of C

Can use const if array elements are not to be modified

Do not need to include the array size when defining an array parameter

Page 366: CPP Slides All

Some Useful Functionsvoid DisplayList(const int A[], int n) {

for (int i = 0; i < n; ++i) {cout << A[i] << " ";

}cout << endl;

}void GetList(int A[], int &n, int MaxN = 100) {

for (n = 0; (n < MaxN) && (cin >> A[n]); ++n) {continue;

}}

Page 367: CPP Slides All

Useful Functions Being Usedconst int MaxNumberValues = 25;int Values[MaxNumberValues];int NumberValues;

GetList(Values, NumberValues, MaxNumberValues);DisplayList(Values, NumberValues);

Page 368: CPP Slides All

SearchingProblem

Determine whether a value key is one of the element values

Does it matter if Element values are not necessarily numbers Element values are not necessarily unique Elements may have key values and other fields

Page 369: CPP Slides All

Sequential List Searchingint Search(const int List[], int m, int Key) {

for (int i = 0; i < m; ++i) {if (List[i] == Key) {

return i;}

}return m;

}

Run time is proportional to number of elements

Page 370: CPP Slides All

Example Invocationcin >> val;int spot = Search(Values, NumberValues, val);if (spot != NumberValues) { // its there, so display it

cout << Values[spot] << endl;}else { // its not there, so add it Values[NumberValues] = val; ++NumberValues;}

Page 371: CPP Slides All

SortingProblem

Arranging elements so that they are ordered according to some desired scheme Standard is non-decreasing order

Why don't we say increasing order?

Major tasks Comparisons of elements Updates or element movement

Page 372: CPP Slides All

Common Sorting TechniquesSelection sort

On ith iteration place the ith smallest element in the ith list location

Bubble sort Iteratively pass through the list and examining

adjacent pairs of elements and if necessary swap them to put them in order. Repeat the process until no swaps are necessary

Page 373: CPP Slides All

Common Sorting TechniquesInsertion sort

On ith iteration place the ith element with respect to the i-1 previous elements In text

Quick sort Divide the list into sublists such that every element

in the left sublist <= to every element in the right sublist. Repeat the Quick sort process on the sublists In text

Page 374: CPP Slides All

SelectionSortvoid SelectionSort(int A[], int n) {

for (int i = 0; i < n-1; ++i) {int k = i;for (int j = i + 1; j < n; ++j) {

if (A[j] < A[k])k = j;

}if (i != k)

swap(A[k], A[i]);}

}

Page 375: CPP Slides All

ComplexitySelectionSort() Question

How long does the function take to run Proportional to n*n time units, where n is the

number of elements in the list

General question How fast can we sort using the perfect comparison-

based method The best possible worst case time is proportional

ton log n time units

Page 376: CPP Slides All
Page 377: CPP Slides All

VectorsFirst-class mechanism for representing lists

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 378: CPP Slides All

Standard Template LibraryWhat is it?

Collection of container types and algorithms supporting basic data structures

What is a container? A generic list representation allowing programmers

to specify which types of elements their particular lists hold Uses the C++ template mechanism

Have we seen this library before? String class is part of the STL

Page 379: CPP Slides All

Sequences deque, list, and vector

Vector supports efficient random-access to elements

STL Container Classes

Associative map, set

Adapters priority_queue, queue, and stack

Page 380: CPP Slides All

Provides list representation comparable in efficiency to arrays

Vector Class Properties

First-class typeEfficient subscripting is possible

Indices are in the range 0 … size of list - 1List size is dynamic

Can add items as we need themIndex checking is possible

Through a member functionIterators

Efficient sequential access

Page 381: CPP Slides All

Example#include <vector>#include <iostream>using namespace std;int main() {

vector<int> A(4, 0); // A: 0 0 0 0A.resize(8, 2); // A: 0 0 0 0 2 2 2 2vector<int> B(3, 1); // B: 1 1 1for (int i = 0; i < B.size(); ++i) {

A[i] = B[i] + 2;} // A: 3 3 3 0 2 2 2 2A = B; // A: 1 1 1return 0;

}

Page 382: CPP Slides All

Some Vector Constructorsvector()

The default constructor creates a vector of zero length

vector(size_type n, const T &val = T()) Explicit constructor creates a vector of length n with

each element initialized to val

vector(const T &V) The copy constructor creates a vector that is a

duplicate of vector V. Shallow copy!

Page 383: CPP Slides All

ConstructionBasic construction

vector<T> List;

Examplevector<int> A; // 0 intsvector<float> B; // 0 floatsvector<Rational> C; // 0 Rationals

Base element type

Container name

Page 384: CPP Slides All

ConstructionBasic construction

vector<T> List(SizeExpression);

Examplevector<int> A(10); // 10 intsvector<float> B(20); // 20 floatsvector<Rational> C(5); // 5 Rationalsint n = PromptAndRead();vector<int> D(n); // n ints

Base element type

Container name

Number of elements to be defaultconstructed

Page 385: CPP Slides All

ConstructionBasic construction

vector<T> List(SizeExpression, Value);

Examplevector<int> A(10, 3); // 10 3svector<float> B(20, 0.2); // 20 0.2sRational r(2/3);vector<Rational> C(5, r); // 5 2/3s

Base element type

Container name

Number of elements to be defaultconstructed

Initial value

Page 386: CPP Slides All

Vector Interfacesize_type size() const

Returns the number of elements in the vector cout << A.size(); // display 3

bool empty() const Returns true if there are no elements in the vector;

otherwise, it returns false

if (A.empty()) { // ...

Page 387: CPP Slides All

Vector Interfacevector<T>& operator = (const vector<T> &V)

The member assignment operator makes its vector representation an exact duplicate of vector V. Shallow copy

The modified vector is returned

vector<int> A(4, 0); // A: 0 0 0 0 vector<int> B(3, 1); // B: 1 1 1 A = B; // A: 1 1 1

Page 388: CPP Slides All

Vector Interfacereference operator [](size_type i)

Returns a reference to element i of the vector Lvalue

const_reference operator [](size_type i) const Returns a constant reference to element i of the

vector Rvalue

Page 389: CPP Slides All

Examplevector<int> A(4, 0); // A: 0 0 0 0const vector<int> B(4, 0); // B: 0 0 0 0

for (int i = 0; i < A.size(); ++i) {A[i] = 3;

} // A: 3 3 3 3

for (int i = 0; i < A.size(); ++i) {cout << A[i] << endl; // lvaluecout << B[i] << endl; // rvalue

}

Page 390: CPP Slides All

Vector Interfacereference at(size_type i)

If i is in bounds, returns a reference to element i of the vector; otherwise, throws an exception

const_reference at(size_type i) const If i is in bounds, returns a constant reference to

element i of the vector; otherwise, throws an exception

Page 391: CPP Slides All

Examplevector<int> A(4, 0); // A: 0 0 0 0

for (int i = 0; i <= A.size(); ++i) {A[i] = 3;

} // A: 3 3 3 3 ??

for (int i = 0; i <= A.size(); ++i) {A.at(i) = 3;

} // program terminates // when i is 4

Page 392: CPP Slides All

Vector Interfacevoid resize(size_type s, T val = T())

The number of elements in the vector is now s. To achieve this size, elements are deleted or

added as necessary Deletions if any are performed at the end Additions if any are performed at the end New elements have value val

vector<int> A(4, 0); // A: 0 0 0 0A.resize(8, 2); // A: 0 0 0 0 2 2 2 2A.resize(3,1); // A: 0 0 0

Page 393: CPP Slides All

Function Examplesvoid GetList(vector<int> &A) {

int n = 0;while ((n < A.size()) && (cin >> A[n])) {

++n;}A.resize(n);

}

vector<int> MyList(3);cout << "Enter numbers: ";GetList(MyList);

Page 394: CPP Slides All

Examplesvoid PutList(const vector<int> &A) {

for (int i = 0; i < A.size(); ++i) {cout << A[i] << endl;

}}

cout << "Your numbers: ";PutList(MyList)

Page 395: CPP Slides All

Vector Interfacepop_back()

Removes the last element of the vector

push_back(const T &val) Inserts a copy of val after the last element of the

vector

Page 396: CPP Slides All

Examplevoid GetValues(vector<int> &A) {

A.resize(0);int Val;while (cin >> Val) {

A.push_back(Val);}

}

vector<int> List;cout << "Enter numbers: ";GetValues(List);

Page 397: CPP Slides All

Overloading >>istream& operator>>(istream& sin, vector<int> &A) {

A.resize(0);int Val;while (sin >> Val) {

A.push_back(Val);}return sin;

}

vector<int> B;cout << "Enter numbers: ";cin >> B;

Page 398: CPP Slides All

Vector Interfacereference front()

Returns a reference to the first element of the vector

const_reference front() const Returns a constant reference to the first element of

the vector

vector<int> B(4,1); // B: 1 1 1 1int& val = B.front();val = 7; // B: 7 1 1 1

Page 399: CPP Slides All

Vector Interfacereference back()

Returns a reference to the last element of the vector

const_reference back() const Returns a constant reference to the last element of the

vector

vector<int> C(4,1); // C: 1 1 1 1int& val = C.back();val = 5; // C: 1 1 1 5

Page 400: CPP Slides All

IteratorsIterator is a pointer to an element

Really pointer abstractionMechanism for sequentially accessing the elements in the list

Alternative to subscripting

There is an iterator type for each kind of vector list

Notes Algorithm component of STL uses iterators Code using iterators rather than subscripting can

often be reused by other objects using different container representations

Page 401: CPP Slides All

Vector Interfaceiterator begin() Returns an iterator that points to the first element of

the vector

iterator end() Returns an iterator that points to immediately beyond

the last element of the vector

vector<int> C(4); // C: 0 0 0 0C[0] = 0; C[1] = 1; C[2] = 2; C[3] = 3;vector<int>::iterator p = C.begin();vector<int>::iterator q = C.end();

Page 402: CPP Slides All

IteratorsTo avoid unwieldy syntax programmers typically use typedef statements to create simple iterator type names

typedef vector<int>::iterator iterator; typedef vector<int>::reverse_iterator reverse_iterator; typedef vector<int>::const_reference const_reference;

vector<int> C(4); // C: 0 0 0 0iterator p = C.begin();iterator q = C.end();

Page 403: CPP Slides All

Iterator Operators* dereferencing operator

Produces a reference to the object to which the iterator p points

*p

++ point to next element in list Iterator p now points to the element that followed the

previous element to which p points++p

-- point to previous element in list Iterator p now points to the element that preceded the

previous element to which p points--p

Page 404: CPP Slides All

typedef vector<int>::iterator iterator;typedef vector<int>::reverse_iterator reverse_iterator;vector<int> List(3);

List[0] = 100; List[1] = 101; List[0] = 102;

iterator p = List.begin();cout << *p; // 100 ++p; cout << *p; // 101--p;cout << *p; // 100reverse_iterator q = List.rbegin();cout << *q; // 102++q;cout << *q; // 101--q;cout << *q; // 102

Page 405: CPP Slides All

Vector Interfaceinsert(iterator pos, const T &val = T())

Inserts a copy of val at position pos of the vector and returns the position of the copy into the vector

erase(iterator pos) Removes the element of the vector at position pos

Page 406: CPP Slides All

SelectionSort Revisitedvoid SelectionSort(vector<int> &A) { int n = A.size();

for (int i = 0; i < n); ++i) {int k = i;for (int j = i + 1; j < n; ++j) {

if (A[j] < A[k])k = j;

}if (i != k)

swap(A[k], A[i]);}

}

Page 407: CPP Slides All

QuickSortQuickSort

Divide the list into sublists such that every element in the left sublist <= to every element in the right sublist

Repeat the QuickSort process on the sublists

void QuickSort(vector<char> &A, int left, int right) {if (left < right) {Pivot(A, left, right);int k = Partition(A, left, right);QuickSort(A, left, k-1);QuickSort(A, k+1, right);}

}

Page 408: CPP Slides All

Picking The Pivot Elementvoid Pivot(vector<char> &A, int left, int right) {

if (A[left] > A[right]) {Swap(A[left], A[right]);

}}

Page 409: CPP Slides All

Decomposing Into Sublistsint Partition(vector<char> &A, int left, int right) {

char pivot = A[left];int i = left;int j = right+1;do {

do ++i; while (A[i] < pivot);do --j; while (A[j] > pivot);if (i < j) {

Swap(A[i], A[j]);}

} while (i < j);Swap(A[j], A[left]);return j;

}

Page 410: CPP Slides All

Sorting Q W E R T Y U I O PQ W E R T Y U I O PI O E P T Y U R W QE O I P T Y U R W QE O I P T Y U R W QE I O P T Y U R W QE I O P T Y U R W QE I O P T Y U R W QE I O P Q Y U R W TE I O P Q Y U R W TE I O P Q R T U W YE I O P Q R T U W YE I O P Q R T U W YE I O P Q R T U W YE I O P Q R T U W YE I O P Q R T U W Y

0 … 9

8 … 7

9 … 9

8 … 9

7 … 6

7 … 9

5 … 5

5 … 9

4 … 3

4 … 9

1 … 2

0 … -1

0 … 2

2 … 2

1 … 0

Page 411: CPP Slides All

InsertionSortvoid InsertionSort(vector<int> &A) {

for (int i = 1; i < A.size(); ++i) {int key = A[i]int j = i - 1;while ((j > 0) && (A[j] > key)) {

A[j+1] = A[j]j = j - 1

}A[j+1] = key

}

Page 412: CPP Slides All

Searching RevisitedProblem

Determine whether a value key is one of the element values in a sorted list

Solution Binary search

Repeatedly limit the section of the list that could contain the key value

Page 413: CPP Slides All

BSearch(const vector<int> &A, int a, int b, int key){if (a > b){

return b+1; }

int m = (a + b)/2if (A[m] == key) {

return m;}else if (a == b) {

return –1;}else if (A[m] < key) {

return BSearch(A, m+1, b, key);}else // A[m] > key

return BSearch(A, a, m-1, key);}

Run time is proportional to

the log of the number of elements

Page 414: CPP Slides All

String Class Revisitedvoid GetWords(vector<string> &List) {

List.resize(0);string s;while (cin >> s) {

List.push_back(s);}

}

Page 415: CPP Slides All

Using GetWords()Suppose standard input contains

A list of words to be read.

vector<string> A;GetWords(A);

Would set A in the following manner: A[0]: "A"A[1]: "list"A[2]: "of"A[3]: "words"A[4]: "to"A[5]: "be"A[6]: "read."

Page 416: CPP Slides All

String Class As Container Class

A string can be viewed as a container because it holds a sequence of characters

Subscript operator is overloaded for string objectsSuppose t is a string object representing "purple"

Traditional t viewt: "purple"

Alternative viewt[0]: 'p't[1]: 'u't[2]: 'r't[3]: 'p't[4]: 'l't[5]: 'e'

Page 417: CPP Slides All

Example#include <cctype>using namespace std;

...

string t = "purple"; t[0] = 'e'; t[1] = 'o'; cout << t << endl; // t: people for (int i = 0; i < t.size(); ++i) { t[i] = toupper(t[i]); }

cout << t << endl; // t: PEOPLE

Page 418: CPP Slides All

Reconsider AWhere

vector<string> A;

Is set in the following mannerA[0]: "A"A[1]: "list"A[2]: "of"A[3]: "words"A[4]: "to"A[5]: "be"A[6]: "read."

Page 419: CPP Slides All

Counting o’sThe following counts number of o’s within A

count = 0;

for (int i = 0; i < A.size(); ++i) {

for (int j = 0; A[i].size(); ++j) {

if (A[i][j] == 'o') {

++count;}

}}

To reference jth character of A[i] we need double subscripts

Size of A[i]

Size of A

Page 420: CPP Slides All

Explicit Two-Dimensional ListConsider definition

vector< vector<int> > A;Then A is a vector< vector<int> >

It is a vector of vectors A[i] is a vector<int>

i can vary from 0 to A.size() - 1

A[i][j] is a int j can vary from 0 to A[i].size() - 1

Page 421: CPP Slides All

Multi-Dimensional ArraysSyntaxbtype mdarray[size_1][size_2] ... [size_k]

Where k - dimensional array mdarray: array identifier size_i: a positive constant expression btype: standard type or a previously defined user

type and is the base type of the array elementsSemantics

mdarray is an object whose elements are indexed by a sequence of k subscripts

the i-th subscript is in the range 0 ... size_i - 1

Page 422: CPP Slides All

Memory Layout

Multidimensional arrays are laid out in row-major orderConsiderint M[2][4];

M is two-dimensional array that consists of 2 subarrays each with 4 elements.

2 rows of 4 elements

The array is assigned to a contiguous section of memory The first row occupies the first portion The second row occupies the second portion

... ...M[0][0] M[0][3]

-- --M[1][0] M[1][3]

-- --

Page 423: CPP Slides All

Identity Matrix Initializationconst int MaxSize = 25;float A[MaxSize][MaxSize];int nr = PromptAndRead();int nc = PromptAndRead();assert((nr <= MaxSize) && (nc <= MaxSize));for (int r = 0; r < nr; ++r) {

for (int c = 0; c < nc; ++c) {A[r][c] = 0;

}A[r][r] = 1;

}

Page 424: CPP Slides All

Matrix Addition Solution

void MatrixAdd(const float A[][MaxCols], const float B[][MaxCols], float C[][MaxCols], int m, int n) {

for (int r = 0; r < m; ++r {for (int c = 0; c < n; ++c) {

C[r][c] = A[r][c] + B[r][c];}

}}

Notice only first brackets are empty

Page 425: CPP Slides All

EzWindows API

A Graphical Application Programmer Interface

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 426: CPP Slides All

Event-based ProgrammingMessages are sent to your program by the operating system

Mouse down Mouse up Key down Key up Refresh Quit Timer

Handle messages by registering a call back

C: User Program

C: SimpleWindow User start

Mouse click

Timer tick

User end

Page 427: CPP Slides All

EzWindows Coordinate System

Use centimeters Metric Simpler to understand

than pixels Device independent Helps introduce

notionof information hidingor encapsulation

Length of window (10 cm)

Height of window (5 cm)

X coordinate: distancefrom left edge of

screen (4 cm)Y coordinate:

distance from topof screen (4 cm)

Page 428: CPP Slides All

Class PositionFor earlier objects, the position was specified by given both an x-coordinate and a y-coordinateWe can now introduce a new object called Position and use it

Page 429: CPP Slides All

Positionclass Position {

public:Position(float x = 0.0, float y = 0.0);float GetXDistance() const;float GetYDistance() const;Position Add(const Position &p) const;

protected:void SetXDistance(float x);void SetYDistance(float y);

private:float XDistance;float YDistance;

};

Position operator+(const Position &x, const Position &y);

Page 430: CPP Slides All

EzWindows Auxiliary Functions

long int GetMilliseconds() Returns the value of a timer that is ticking

continuously. The resolution of the timer is milliseconds.

void Terminate() Sends a terminate message to the EzWindows

window manager.

Page 431: CPP Slides All

Class SimpleWindowWriting text in a windowvoid SimpleWindow::RenderText(const Position &UpperLeft, const Position &LowerRight, const string &Msg = "Message", const color &TextColor = Black, const color &BackGroundColor = White)

First coordinate of thebounding box

Second coordinate ofthe bounding box

Message

Page 432: CPP Slides All

Hello EzWindows#include <assert.h>#include "ezwin.h"

// Create a 10 x 4 windowSimpleWindow HelloWindow("Hello EzWindows", 10.0, 4.0, Position(5.0, 6.0));

// ApiMain(): create a window and display greetingint ApiMain() {

HelloWindow.Open();assert(HelloWindow.GetStatus() == WindowOpen);

// Get Center of WindowPosition Center = HelloWindow.GetCenter();

Page 433: CPP Slides All

Hello EzWindows // Create bounding box for text

Position UpperLeft = Center + Position(-1.0, -1.0);Position LowerRight = Center + Position(1.0, 1.0);

// Display the textHelloWindow.RenderText(UpperLeft, LowerRight, "Hello EzWindows", Black, White);

return 0;}

Page 434: CPP Slides All

Hello EzWindows// ApiEnd(): shutdown the windowint ApiEnd() {

HelloWindow.Close();

return 0;}

Page 435: CPP Slides All

Class SimpleWindowSimple Window constructor

SimpleWindow::SimpleWindow(const string &t =

"Untitled“float w = 8,float h = 8,const Position &p = Position(0,0)

)

Page 436: CPP Slides All

Bitmaps

Page 437: CPP Slides All

Class BitMapUses BitMapStatus

enum BitMapStatus {NoBitMap, BitMapOkay, NoWindow

};

Page 438: CPP Slides All

Class BitMapClass BitMap can display .bmp files in a SimpleWindow window

BitMap’s constructor isBitMap::BitMap(SimpleWindow &w)

Additional key member functions areBitMapStatus BitMap::Load(string Filename)BitMapStatus BitMap::GetStatus() constvoid BitMap::SetPosition(const Position &p)int BitMap::Draw()int BitMap::Erase()int BitMap::IsInside(const Position &p) const

Page 439: CPP Slides All

Fun with Pictures// Display a bit map image of the authors in the // center of a window#include <assert.h>#include "bitmap.h"

// Open a window to display photographSimpleWindow PhotoWindow("The Authors", 10.0, 7.0, Position(5.0, 3.0));

// ApiMain(): display a bitmap photoint ApiMain() {

PhotoWindow.Open();assert(PhotoWindow.GetStatus() == WindowOpen);const Position WindowCenter = PhotoWindow.GetCenter();

Page 440: CPP Slides All

Fun with Pictures// Create a bitmapBitMap Photo(PhotoWindow);// Load the imagePhoto.Load("photo.bmp");assert(Photo.GetStatus() == BitMapOkay);// Compute position of logo so it is centeredPosition PhotoPosition = WindowCenter + Position(-.5 * Photo.GetWidth(), -.5 * Photo.GetHeight());Photo.SetPosition(PhotoPosition);// Draw bitmap and we’re donePhoto.Draw();return 0;

}

Page 441: CPP Slides All

Fun with Pictures

Page 442: CPP Slides All

Mouse EventsBefore we can react to a mouse event in a SimpleWindow

Must tell window what function to call when an event occurs Registering a callback

To register a callback use the SimpleWindow member function SetMouseClickCallback.

W1.SetMouseClickCallback(f);

Says if the mouse is clicked in window W1, call function f() f() is passed a Position that is the coordinate of the

location of the mouse when the button was clicked

Page 443: CPP Slides All

Mouse Eventsint ApiMain() {

// Open the windowW1.Open(); assert(W1.GetStatus() == WindowOpen);

// Load the imageB.Load("wizards.bmp"); assert(B.GetStatus() == BitMapOkay);

// Display the bit maps at a starting positionB.SetPosition(Position(1.0, 1.0));B.Draw();

// Register the callbacks for each windowW1.SetMouseClickCallback(ReceiveMouseClick);

return 0;}

Page 444: CPP Slides All

Mouse Events#include <assert.h>#include "bitmap.h"SimpleWindow W1("Window One", 10.0, 7.0, Position(1.0,

1.0));BitMap B(W1); // Define a bitmap// Mouse callback functionint ReceiveMouseClick(const Position &p) {

// Erase the bitmapB.Erase();// Set its new position and display itB.SetPosition(p);B.Draw();return 1;

}

Page 445: CPP Slides All

Timer EventsThe SimpleWindow class supports a timer mechanism

You can set a timer to go off periodically

When the timer goes off, a call back is made to the function specified by the user

Page 446: CPP Slides All

Timer Functionsvoid SimpleWindow::SetTimerCallback( TimerTickCallbackFunction f)

Registers a callback for a timer tick Function f() will be called when a timer tick occurs. The function f() must be declared to take no

parameters, and it should return an int The return value of f() indicates whether the event

was handled successfully A value of 1 is to indicate success A value of 0 is to indicate an error occurred

Page 447: CPP Slides All

Timer Functionsint SimpleWindow::StartTimer(int Interval)

Starts timer running Parameter Interval is the number of milliseconds

between timer events The return value indicates whether the timer was

successfully started A return value of 1 indicates success A return value of 0 indicates the timer could not be set

up

void SimpleWindow::StopTimer() Turns timer off

Page 448: CPP Slides All

#include <assert.h>#include "bitmap.h“

SimpleWindow W1("Fun", 15.0, 9.0, Position(1.0, 1.0));

BitMap B(W1); // Define a bitmap

// W1TimerEvent(): move bitmap to a new locationint W1TimerEvent() {

// Erase the bitmapB.Erase(); // Compute a new position and display it// Make sure the bitmap is completely in the windowint XCoord = Uniform(1, W1.GetWidth());if (XCoord + B.GetWidth() > W1.GetWidth())

XCoord = XCoord - B.GetWidth();int YCoord = Uniform(1, W1.GetHeight());if (YCoord + B.GetHeight() > W1.GetHeight())

YCoord = YCoord - B.GetHeight();B.SetPosition(Position(XCoord, YCoord));B.Draw();

}

Example

Page 449: CPP Slides All

Exampleint ApiMain() {

W1.Open(); // Open the windowassert(W1.GetStatus() == WindowOpen);B.Load("davidson.bmp"); // Load the imageassert(B.GetStatus() == BitMapOkay);

// Display the bit maps at a starting positionB.SetPosition(Position(1.0, 1.0));B.Draw();

// Register the callbacks for each window// and start the timers to go off every 500 msW1.SetTimerCallback(W1TimerEvent);W1.StartTimer(500);return 0;

}

Page 450: CPP Slides All

Exampleint ApiEnd() {

// Stop the timers and close the windowsW1.StopTimer();W1.Close();return 0;

}

Page 451: CPP Slides All

Pointers and Dynamic ObjectsMechanisms for developing flexible list representations

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 452: CPP Slides All

UsefulnessMechanism in C++ to pass command-line parameters to a program

This feature is less important now with the use of graphical interfaces

Mechanism in C++ to pass command-line parameters to a program

This feature is less important now with the use of graphical interfaces

Necessary for dynamic objects Objects whose memory is acquired during program

execution as the result of a specific program request Dynamic objects can survive the execution of the

function in which they are acquired Dynamic objects enable variable-sized lists

Page 453: CPP Slides All

Categorizing ExpressionsLvalue expressions

Represent objects that can be evaluated and modifiedRvalue expressions

Represent objects that can only be evaluatedConsiderint a;vector<int> b(3);int c[3];a = 1; // a: lvaluec[0] = 2*a + b[0]; // c[0], a, b[0]: lvalues

Observation Not all lvalues are the names of objects

Page 454: CPP Slides All

BasicsPointer

Object whose value represents the location of another object

In C++ there are pointer types for each type of object Pointers to int objects Pointers to char objects Pointers to RectangleShape objects

Even pointers to pointers Pointers to pointers to int objects

Page 455: CPP Slides All

Examples of uninitialized pointers

int *iPtr; // iPtr is a pointer to an intchar *s; // s is a pointer to a charRational *rPtr; // rPtr is a pointer to a // Rational

Examples of initialized pointersint i = 1;char c = 'y';int *ptr = &i; // ptr is a pointer to int ichar *t = &c; // t is a pointer to a char c

Indicates pointer object

Indicates to take the address of the object

SyntaxExamples of uninitialized pointers

int *iPtr; // iPtr is a pointer to an intchar *s; // s is a pointer to a charRational *rPtr; // rPtr is a pointer to a // Rational

Indicates pointer object

Page 456: CPP Slides All

Memory Depictionint i = 1;char c = 'y';int *ptr = &i;char *t = &c

Page 457: CPP Slides All

Indirection OperatorAn asterisk has two uses with regard to pointers

In a definition, it indicates that the object is a pointerchar *s; // s is of type pointer to char

In expressions, when applied to a pointer it evaluates to the object to which the pointer pointsint i = 1;int *ptr = &i; // ptr points to i*ptr = 2;cout << i << endl; // display a 2

* indicates indirection or dereferencing*ptr is an lvalue

Page 458: CPP Slides All

Address Operator& use is not limited to definition initializationint i = 1;int j = 2;int *ptr;ptr = &i; // ptr points to location of i*ptr = 3; // contents of i are updatedptr = &j; // ptr points to location of j*ptr = 4; // contents of j are updatedcout << i << " " << j << endl;

Page 459: CPP Slides All

Null Address0 is a pointer constant that represents the empty or null address

Its value indicates that pointer is not pointing to a valid object

Cannot dereference a pointer whose value is nullint *ptr = 0;cout << *ptr << endl; // invalid, ptr // does not point to // a valid int

Page 460: CPP Slides All

Member IndirectionConsider

Rational r(4,3);Rational rPtr = &r;

To select a member of r using rPtr and member selection, operator precedence requires

(*rPtr).Insert(cout);

Invokes member Insert() of the object to which rPtr points (r)

ConsiderRational r(4,3);Rational rPtr = &r;

To select a member of r using rPtr and member selection, operator precedence requires

(*rPtr).Insert(cout);

This syntax is clumsy, so C++ provides the indirect member selector operator ->

rPtr->Insert(cout);

Invokes member Insert() of the object to which rPtr points (r)

Invokes member Insert() of the object to which rPtr points (r)

Page 461: CPP Slides All

Traditional Pointer Usagevoid IndirectSwap(char *Ptr1, char *Ptr2) {

char c = *Ptr1;*Ptr1 = *Ptr2;*Ptr2 = c;

}

int main() {char a = 'y';char b = 'n';IndirectSwap(&a, &b);cout << a << b << endl;return 0;

}

In C, there are no reference parameters. Pointers are used to simulate them.

Page 462: CPP Slides All

Constants and PointersA constant pointer is a pointer such that we cannot change the location to which the pointer pointschar c = 'c';const char d = 'd';char * const ptr1 = &c;ptr1 = &d; // illegal

A constant pointer is a pointer such that we cannot change the location to which the pointer pointschar c = 'c';const char d = 'd';char * const ptr1 = &c;ptr1 = &d; // illegal

A pointer to a constant value is a pointer object such that the value at the location to which the pointer points is considered constantconst char *ptr2 = &d;*ptr2 = 'e'; // illegal: cannot change d // through indirection with ptr2

Page 463: CPP Slides All

Local objects and parameters

Object memory is acquired automatically

Object memory is returned automatically when object goes out of scope

Dynamic objects

Object memory is acquired by program with an allocation request new operation

Dynamic objects can exist beyond the function in which they were allocated

Object memory is returned by a deallocation request delete operation

Local objects and parameters

Object memory is acquired automatically

Dynamic objects

Object memory is acquired by program with an allocation request new operation

DifferencesLocal objects and parameters

Dynamic object

Page 464: CPP Slides All

Operation specifies The type and number of objects

If there is sufficient memory to satisfy the request A pointer to sufficient memory is returned by the

operationIf there is insufficient memory to satisfy the request

An exception is generated An exception is an error state/condition which if

not handled (corrected) causes the program to terminate

General New Operation Behavior

Memory for dynamic objects Requested from the free store

Free store is memory controlled by operating system

Page 465: CPP Slides All

The Basic New FormSyntax

Ptr = new SomeType ; Where

Ptr is a pointer of type SomeType

Beware The newly acquired memory is uninitialized unless

there is a default SomeType constructor

Page 466: CPP Slides All

Examplesint *iptr = new int;Rational *rptr = new Rational;

—iptr

Uninitialized int object

0/1rptr

Rational object with defaultinitialization

Page 467: CPP Slides All

Another Basic New FormSyntax

SomeType *Ptr = new SomeType(ParameterList);

Where

Ptr is a pointer of type SomeType

Initialization The newly acquired memory is initialized using a

SomeType constructor ParameterList provides the parameters to the constructor

Page 468: CPP Slides All

Examplesint *iptr = new int(10);Rational *rptr = new Rational(1,2);

10iptr

1/2rptr

Page 469: CPP Slides All

The Primary New FormSyntax

P = new SomeType [Expression] ;

Where P is a pointer of type SomeType Expression is the number of contiguous objects of

type SomeType to be constructed -- we are making a list

Note The newly acquired list is initialized if there is a

default SomeType constructor

Because of flexible pointer syntax P can be considered to be an array

Page 470: CPP Slides All

Examplesint *A = new int [3];Rational *R = new Rational[2];A[1] = 5;Rational r(2/3);R[0] = r;

—A

2/3R

5

0/1

Page 471: CPP Slides All

Right Array For The Jobcout << "Enter list size: ";int n;cin >> n;int *A = new int[n];GetList(A, n);SelectionSort(A, n);DisplayList(A, n);

Note

Use of the container classes of the STL is preferred from a software engineering viewpoint

Example vector class

Page 472: CPP Slides All

Delete OperatorsForms of request

delete P; // used if storage came from newdelete [] P; // used if storage came from new[]

Storage pointed to by P is returned to free store

P is now undefined

Page 473: CPP Slides All

Cleaning Upint n;cout << "Enter list size: ";cin >> n;int *A = new int[n];GetList(A, n);SelectionSort(A, n);DisplayList(A, n);delete [] A;

Page 474: CPP Slides All

Dangling Pointer Pitfallint *A = new int[5];for (int i = 0; i < 5; ++i) A[i] = i;int *B = A;

delete [] A;

A

B0 1 2 3 4

A

B

Locations do not belong to program—

?

Page 475: CPP Slides All

Memory Leak Pitfallint *A = new int [5];for (int i = 0; i < 5; ++i) A[i] = i;

A = new int [5];

A 0 1 2 3 4

— — — — —

These locations cannot beaccessed by program

A 0 1 2 3 4

Page 476: CPP Slides All

A Simple Dynamic List TypeWhat we want

An integer list data type IntList with the basic features of the vector data type from the Standard Template Library

Features and abilities

True object Can be passed by value and reference Can be assigned and copied

Inspect and mutate individual elements Inspect list size Resize list Insert and extract a list

Page 477: CPP Slides All

Sample IntList UsageIntList A(5, 1);IntList B(10, 2);IntList C(5, 4);for (int i = 0, i < A.size(); ++i) {

A[i] = C[i];}cout << A << endl; // [ 4 4 4 4 4 ]A = B;A[1] = 5;cout << A << endl; // [ 5 2 2 2 2 2 2 2 2 2 ]

Page 478: CPP Slides All

IntList Definitionclass IntList {

public:// constructorsIntList(int n = 10, int val = 0);IntList(const int A[], int n);IntList(const IntList &A);// destructor~IntList();// inspector for size of the listint size() const;// assignment operatorIntList & operator=(const IntList &A);

Page 479: CPP Slides All

IntList Definition (continued)

public:// inspector for element of constant listconst int& operator[](int i) const;// inspector/mutator for element of// nonconstant listint& operator[](int i);// resize listvoid resize(int n = 0, int val = 0);// convenience for adding new last elementvoid push_back(int val);

Page 480: CPP Slides All

IntList Definition (continued)

private:// data membersint *Values; // pointer to elementsint NumberValues; // size of list

};

// IntList auxiliary operators -- nonmembers

ostream& operator<<(ostream &sout, const IntList &A);

istream& operator>>(istream &sin, IntList &A);

Page 481: CPP Slides All

Default ConstructorIntList::IntList(int n, int val) {

assert(n > 0);NumberValues = n;Values = new int [n];assert(Values);for (int i = 0; i < n; ++i) {

Values[i] = val;}

}

Page 482: CPP Slides All

Gang of Three RuleIf a class has a data member that points to dynamic memory then that class normally needs a class-defined

Copy constructor Constructor that builds an object out of an object

of the same type

Member assignment operator Resets an object using another object of the same

type as a basis

Destructor Anti-constructor that typically uses delete the

operator on the data members that point to dynamic memory

Page 483: CPP Slides All

Why A Tailored Copy Constructor

Suppose we use the default copy constructorIntList A(3, 1);IntList B(A);

And then A[2] = 2;

Then B[2] is changed! Not what a client would expect

Implication Must use tailored copy constructor

A

B

1 2 13

3

Page 484: CPP Slides All

Tailored Copy ConstructorIntList::IntList(const IntList &A) {

NumberValues = A.size();Values = new int [size()];assert(Values);for (int i = 0; i < size(); ++i)

Values[i] = A[i];}

What kind of subscripting is being performed?

Page 485: CPP Slides All

Gang Of ThreeWhat happens when an IntList goes out of scope?

If there is nothing planned, then we would have a memory leak

Need to have the dynamic memory automatically deleted

Define a destructor A class object going out of scope automatically

has its destructor invoked

IntList::~IntList() { delete [] Values;}

Notice the tilde

Page 486: CPP Slides All

First Assignment AttemptAlgorithm

Return existing dynamic memory

Acquire sufficient new dynamic memory

Copy the size and the elements of the source object to the target element

Page 487: CPP Slides All

Initial Implementation (Wrong)

IntList& operator=(const IntList &A) {NumberValues = A.size();delete [] Values;Values = new int [NumberValues ];assert(Values);for (int i = 0; i < A.size(); ++i) Values[i] = A[i];return A;

}

Consider what happens with the code segmentIntList C(5,1);C = C;

Page 488: CPP Slides All

This PointerConsider

this

Inside a member function or member operator this is a pointer to the invoking object

IntList::size() { return NumberValues;}

or equivalently

IntList::size() { return this->NumberValues;}

Page 489: CPP Slides All

Member Assignment Operator

IntList& IntList::operator=(const IntList &A) {if (this != &A) {

delete [] Values;NumberValues = A.size();Values = new int [A.size()];assert(Values);for (int i = 0; i < A.size(); ++i) { Values[i] = A[i];}

}return *this;

}Notice the different uses of the subscript operator

Why the asterisk?

Page 490: CPP Slides All

Accessing List Elements// Compute an rvalue (access constant element)const int& IntList::operator[](int i) const {assert((i >= 0) && (i < size()));return Values[i];

}

// Compute an lvalueint& IntList::operator[](int i) {assert((i >= 0) && (i < size()));return Values[i];

}

Page 491: CPP Slides All

Stream OperatorsShould they be members?

class IntList {// ...ostream& operator<<(ostream &sout);// ...

};Answer is based on the form we want the operation to take

IntList A(5,1);A << cout; // member form (unnatural)cout << A; // nonmember form (natural)

Page 492: CPP Slides All

Beware of FriendsIf a class needs to

Can provide complete access rights to a nonmember function, operator, or even another class Called a friend

Declaration example

class IntList {// ...friend ostream& operator<< (

ostream &sout, const IntList &A);// ...

};

Page 493: CPP Slides All

Implementing Friend <<ostream& operator<<(ostream &sout, const IntList &A){ sout << "[ "; for (int i = 0; i < A.NumberValues; ++i) {

sout << A.Values[i] << " "; } sout << "]"; return sout;

}

Is there any need for this friendship?

Page 494: CPP Slides All

Proper << Implementationostream& operator<<(ostream &sout, const IntList &A){ sout << "[ "; for (int i = 0; i < A.size(); ++i) {

sout << A[i] << " "; } sout << "]"; return sout;

}

Page 495: CPP Slides All

InheritanceMechanism for deriving new classes from existing classes

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 496: CPP Slides All

Think of a Bicycle

Page 497: CPP Slides All

Think of a Tandem Bike

Page 498: CPP Slides All

Think of a Racing Bike

Page 499: CPP Slides All

Think of a Mountain Bike

Page 500: CPP Slides All

Thinking About BicyclesA tandem bicycle is a kind of bicycle

Bicycle with two seats

A mountain bicycle is a kind of bicycle Bicycle with shocks

A racing bicycle is a kind of bicycle Lightweight aerodynamic construction

Tandem, mountain, and racing bicycles are specialized bicycles

Page 501: CPP Slides All

Wouldn’t It Be NiceBe able to create specialized program objects without starting from scratch

Blinking rectangles Moving bitmaps Arbitrary precision numbers

Inheritance is the object-oriented programming mechanism for specialization

Page 502: CPP Slides All

Ability to define new classes of objects using existing classes as a basis

InheritanceAbility to define new classes of objects using existing classes as a basis

The new class inherits the attributes and behaviors of the parent classes

Ability to define new classes of objects using existing classes as a basis

The new class inherits the attributes and behaviors of the parent classes

New class is aspecialized versionof the parent class Bicycle

MountainBikes

RacingBikes

TandemBikes

is-a relationships

Page 503: CPP Slides All

A natural way to reuse code Programming by extension rather than reinvention Object-oriented paradigm is well-suited for this style

ofprogramming

Inheritance

Bicycle

MountainBikes

RacingBikes

TandemBikes

is-a relationships

A natural way to reuse code Programming by extension rather than reinvention Object-oriented paradigm is well-suited for this style

ofprogramming

Terminology Base class (superclass) Derived class (subclass)

Page 504: CPP Slides All

class RectangleShape {public:

RectangleShape(SimpleWindow &W, float XCoord, float YCoord, const color &Color, float Width, float Height);void Draw();color GetColor() const;void GetSize(float &Width, float &Height) const;void GetPosition(float &x, float &y) const;float GetWidth() const;float GetHeight() const;SimpleWindow& GetWindow() const;void SetColor(const color &Color);void SetPosition(float x, float y);void SetSize(float Width, float Height);

private:SimpleWindow &Window;float XCenter;float YCenter;color Color;float Width;float Height;

};

Before Inheritance

Page 505: CPP Slides All

Before Inheritanceclass CircleShape {

public:CircleShape(SimpleWindow &W, float x, float y, const color &Color, float Diameter);void Draw();color GetColor() const;float GetSize() const;void GetPosition(float &x, float &y) const;SimpleWindow& GetWindow() const;void SetColor(const color &Color);void SetPosition(float x, float y);void SetSize(float Diameter);

private:SimpleWindow &Window;float XCenter;float YCenter;color Color;float Diameter;

};

Page 506: CPP Slides All

ShapesHierarchy

C: ShapeDM: Color

MF: GetColor(), SetColor()

C: RectangleShapeDM: Width, Height

MF: Draw(), GetWidth(),GetHeight(), SetSize()

C: TriangleShapeDM: SideLength

MF: Draw(),GetSideLength(),

SetSize()

C: WindowObjectDM: Location, Window

MF: GetPosition(), GetWindow(), SetPosition()

C: Label

C: EllipseShapeDM: Width, Height

MF: Draw(),GetWidth(),

GetHeight(), SetSize()

Page 507: CPP Slides All

Class WindowObjectclass WindowObject {

public:WindowObject(SimpleWindow &w, const Position &p);Position GetPosition() const;SimpleWindow& GetWindow() const;void SetPosition(const Position &p);

private:SimpleWindow &Window;Position Location;

};

Page 508: CPP Slides All

WindowObject ConstructorWindowObject::WindowObject(SimpleWindow &w, const Position &p) : Window(w), Location(p) { // No body needed}

Members are initializedin class definition order

Page 509: CPP Slides All

WindowObject InspectorsPosition WindowObject::GetPosition() const {

return Location;}

SimpleWindow& WindowObject::GetWindow() const {return Window;

}

Page 510: CPP Slides All

WindowObject Mutatorvoid WindowObject::SetPosition(const Position &p) {

Location = p;}

Page 511: CPP Slides All

Defining a Derived Class

class DerivedClass : public BaseClass { public:

// public section ... private:

// private section ...};

Derived class name

Access specifier(usually public)

Class name ofbase class

Page 512: CPP Slides All

Declaring a Derived Class

class Shape : public WindowObject {public:

Shape(SimpleWindow &w, const Position &p, const color &c = Red);color GetColor() const;void SetColor(const color &c);

private:color Color;

};

Read this as Shape is a kind of WindowObject

Shape inherits WindowObjectmembers Window, Location,GetPosition(), GetWindow(),and SetPosition()

Page 513: CPP Slides All

Implementing A Derived Class Constructor

Derivedclassname

Derivedclass

constructorparameter

list

Baseclassname

Base classconstructor

parameter list(sublist of PList)

Derived cass datamember initialization list

(sublist of PList)

DClass::DClass(PList) : BClass(BList), DMbrList {// Body of derived class constructor...

};

Page 514: CPP Slides All

Implementing a Derived Class

Shape::Shape(SimpleWindow &w, const Position &p, const color &c) : WindowObject(w, p), Color(c) { // No body needed}

color Shape::GetColor() const {return Color;

}

void Shape::SetColor(const color &c) {assert(c >= 0 && c < MaxColors);Color = c;

}

Page 515: CPP Slides All

Basic Shapes

Width

Height

SideLength

RectangleShape TriangleShape

WIdth

Height

EllipseShape

Page 516: CPP Slides All

TriangleShape#include "shape.h"class TriangleShape : public Shape {

public:TriangleShape(SimpleWindow &w, const Position &p, const color &c = Red, float slen = 1);float GetSideLength() const;void SetSize(float slen);void Draw();

private:float SideLength;

};

Page 517: CPP Slides All

EllipseShape#include "shape.h"class EllipseShape : public Shape {

public:EllipseShape(SimpleWindow &w, const Position &Center, const color &c = Red, float Width = 1, float Height = 2);float GetWidth() const;float GetHeight() const;void Draw();void SetSize(float Width, float Height);

private:float Width;float Height;

};

Page 518: CPP Slides All

RectangleShape#include "shape.h"class RectangleShape : public Shape {

public:RectangleShape(SimpleWindow &w, const Position &Center, const color &c = Red, float Width = 1, float Width = 2);float GetWidth() const;float GetHeight() const;void Draw();void SetSize(float Width, float Height);private:float Width;float Height;

};

Page 519: CPP Slides All

TriangleShape::Draw()void TriangleShape::Draw() {

const float Pi = 3.1415;const Position Center = GetPosition();const float SLength = GetSideLength();

// Compute c, distance from center of triangle// to the top vertex, and a, the distance from// the center to the base of the trianglefloat c = SLength / (2.0 * cos(30 * Pi / 180.0));float a = tan(30 * Pi / 180.0) * .5 * SLength;

Page 520: CPP Slides All

TriangleShape::Draw()// Create an array containing the positions of// the vertices of the triangle

vector Position TrianglePoints[3];TrianglePoints[0] = Center + Position(0, -c),TrianglePoints[1] = Center + Position(-.5 * SLength, a);TrianglePoints[2] = Center + Position(.5 * SLength, a);

// Draw the triangle

GetWindow().RenderPolygon(TrianglePoints, 3, GetColor(), HasBorder());

}

Page 521: CPP Slides All

Using Shapes#include "rect.h"#include "ellipse.h"#include "triangle.h"SimpleWindow Window("TestShapes", 17.0, 7.0,

Position(4.0, 4.0));int ApiMain() {

Window.Open();TriangleShape T(Window, Position(3.5, 3.5), Red, 3.0);T.Draw();RectangleShape R(Window, Position(8.5, 3.5), Yellow, 3.0, 2.0);R.Draw();EllipseShape E(Window, Position(13.5, 3.5), Green, 3.0, 2.0);E.Draw();return 0;

}

Page 522: CPP Slides All

Fun with Shapes

Page 523: CPP Slides All

Cleaning Up

int ApiEnd()TWindow.Close();return 0;

}

Page 524: CPP Slides All

Inheritance and Member Access

class SomeClass {public:

void MemberFunction();int MyPublicData;

protected:int MyProtectedData;

private:int MyPrivateData;

};

void SomeClass::MemberFunction() {MyPublicData = 1; // access allowedMyProtectedData = 2; // access allowedMyPrivateData = 3; // access allowed

}

Page 525: CPP Slides All

Inheritance and Member Access

void NonMemberFunction() {SomeClass C;C.MyPublicData = 1; // access allowedC.MyProtectedData = 2; // illegalC.MyPrivateData = 3; // illegal

}

Page 526: CPP Slides All

Inheritance and Member Access

class BaseClass {public: int MyPublicData;protected: int MyProtectedData;private: int MyPrivateData;

};class DerivedClass : public BaseClass {

public: void DerivedClassFunction();// ...

};void DerivedClass::DerivedClassFunction() {

MyPublicData = 1; // access allowedMyProtectedData = 2; // access allowedMyPrivateData = 3;// illegal

}

Page 527: CPP Slides All

Controlling InheritanceInheritance Type Base class member

access Derived class member access

public public public protected protected private inaccessible public protected protected protected protected private inaccessible public private private protected private private inaccessible

Page 528: CPP Slides All
Page 529: CPP Slides All

Templates and PolymorphismGeneric functions and classes

JPC and JWD © 2002 McGraw-Hill, Inc.

Page 530: CPP Slides All

Polymorphic FunctionsWhat are they?

Generic functions that can act upon objects of different types The action taken depends upon the types of the

objects

Where have we seen them before

Where have we seen them before? Function overloading

Define functions or operators with the same name Rational addition operator + Function Min() for the various numeric types

Primitive polymorphism

Page 531: CPP Slides All

Polymorphic FunctionsTemplates

Generate a function or class at compile time

Where have we seen them before?

Templates Generate a function or class at compile time

Where have we seen them before? Standard Template Library

Vector and other container classes

Templates Generate a function or class at compile time

Where have we seen them before? Standard Template Library

Vector and other container classes

True polymorphism Choice of which function to execute is made during

run time C++ uses virtual functions

Templates Generate a function or class at compile time

Page 532: CPP Slides All

Function TemplatesCurrent scenario

We rewrite functions Min(), Max(), and InsertionSort() for many different types

There has to be a better way

Function template Describes a function format that when instantiated

with particulars generates a function definition Write once, use multiple times

Page 533: CPP Slides All

An Example Function Template

template <class T> T Min(const T &a, const T &b) { if (a < b)

return a; else

return b; }

Indicates a template is being defined Indicates T is our formal

template parameter

Instantiated functions will return a value

whose type is the actual template

parameter

Instantiated functions require

two actual parameters of the same type.

Their type will be the actual value

for T

Page 534: CPP Slides All

Min TemplateCode segmentint Input1 = PromptAndRead();int Input2 = PromptAndRead();cout << Min(Input1, Input2) << endl;

Causes the following function to be generated from our templateint Min(const int &a, const int &b) {if (a < b) return a;else return b;

}

Page 535: CPP Slides All

Min TemplateCode segmentdouble Value1 = 4.30;double Value2 = 19.54;cout << Min(Value1, Value2) << endl;

Causes the following function to be generated from our templatedouble Min(const double &a, const double &b) {if (a < b) return a;else return b;

}

Page 536: CPP Slides All

Min TemplateCode segmentRational r(6,21);Rational s(11,29);cout << Min(r, s) << endl;

Causes the following function to be generated from our templateRational Min(const Rational &a, const Rational &b) {if (a < b) return a;else return b;

}

Operator < needs to be defined for for the actual template parameter type. If < is not defined, then a compile-time error occurs

Page 537: CPP Slides All

Function Templates FactsLocation in program files

In current compilers Template definitions are part of header files

Possible template instantiation failure scenariocout << min(7, 3.14); // different parameter // types

Page 538: CPP Slides All

Generic Sortingtemplate <class T>void InsertionSort(T A[], int n) {

for (int i = 1; i < n; ++i) {if (A[i] < A[i-1]) { T val = A[i]; int j = i; do { A[j] = A[j-1]; --j; } while ((j > 0) && (val < A[j-1])); A[j] = val;}}

}

Page 539: CPP Slides All

STL’s Template FunctionsSTL provides template definitions for many programming tasks

Use them! Do not reinvent the wheel!

STL provides template definitions for many programming tasks

Use them! Do not reinvent the wheel!

Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort()

STL provides template definitions for many programming tasks

Use them! Do not reinvent the wheel!

Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort()

Comparing equal()

STL provides template definitions for many programming tasks

Use them! Do not reinvent the wheel!

Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort()

Comparing equal()

Rearranging and copying unique(), replace(), copy(), remove(), reverse(), random_shuffle(), merge()

STL provides template definitions for many programming tasks

Use them! Do not reinvent the wheel!

Searching and sorting find(), find_if(), count(), count_if(), min(), max(), binary_search(), lower_bound(), upper_bound(), sort()

Comparing equal()

Rearranging and copying unique(), replace(), copy(), remove(), reverse(), random_shuffle(), merge()

Iterating for_each()

Page 540: CPP Slides All

Class TemplatesRules

Type template parameters

Value template parameters Place holder for a value Described using a known type and an identifier

name

Template parameters must be used in class definition described by template

Implementation of member functions in header file Compilers require it for now

Page 541: CPP Slides All

A Generic Array Representation

We will develop a class Array Template version of IntList

Provides additional insight into container classes of STL

Page 542: CPP Slides All

Homegrown Generic ArraysArray<int> A(5, 0); // A is five 0'sconst Array<int> B(6, 1); // B is six 1'sArray<Rational> C; // C is ten 0/1'sA = B;A[5] = 3;A[B[1]] = 2;cout << "A = " << A << endl; // [ 1 2 1 1 1 3 ]cout << "B = " << B << endl; // [ 1 1 1 1 1 1 ]cout << "C = " << D << endl; // [ 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 ]

Page 543: CPP Slides All

template <class T> class Array {

public:Array(int n = 10, const T &val = T());Array(const T A[], int n);Array(const Array<T> &A);~Array();int size() const { return NumberValues;}Array<T> & operator=(const Array<T> &A);const T& operator[](int i) const;T& operator[](int i);

private:int NumberValues;T *Values;

};

Optional value is default constructed

Inlined function

Page 544: CPP Slides All

Auxiliary Operatorstemplate <class T> ostream& operator<< (ostream &sout, const Array<T> &A);

template <class T> istream& operator>> (istream &sin, Array<T> &A);

Page 545: CPP Slides All

Default Constructortemplate <class T> Array<T>::Array(int n, const T &val) { assert(n > 0);

NumberValues = n;Values = new T [n];assert(Values);for (int i = 0; i < n’ ++ i) {

Values[i] = A[i]; }

}

Page 546: CPP Slides All

Copy Constructortemplate <class T> Array<T>::Array(const Array<T> &A) {

NumberValues = A.size();Values = new T [A.size()];assert(Values);for (int i = 0; i < A.size(); ++i) {

Values[i] = A[i];}

}

Page 547: CPP Slides All

Destructortemplate <class T> Array<T>::~Array() {

delete [] Values;}

Page 548: CPP Slides All

Member Assignmenttemplate <class T> Array<T>& Array<T>::operator=(const Array<T> &A) {

if ( this != &A ) {if (size() != A.size()) { delete [] Values; NumberValues = A.size(); Values = new T [A.size()]; assert(Values);}for (int i = 0; i < A.size(); ++i) { Values[i] = A[i];}

}return *this;

}

Page 549: CPP Slides All

Inspector for Constant Arraystemplate <class T> const T& Array<T>::operator[](int i) const {

assert((i >= 0) && (i < size()));return Values[i];

}

Page 550: CPP Slides All

Nonconstant Inspector/Mutatortemplate <class T> T& Array<T>::operator[](int i) {

assert((i >= 0) && (i < size()));return Values[i];

}

Page 551: CPP Slides All

Generic Array Insertion Operatortemplate <class T> ostream& operator<<(ostream &sout, const Array<T> &A){

sout << "[ "; for (int i = 0; i < A.size(); ++i) {

sout << A[i] << " "; }

sout << "]"; return sout;

}

Can be instantiated for whatever type of Array we need

Page 552: CPP Slides All

Specific Array Insertion Operator

Suppose we want a different Array insertion operator for Array<char> objects

ostream& operator<<(ostream &sout, const Array<char> &A){

for (int i = 0; i < A.size(); ++i) { sout << A[i];

} return sout;

}

Page 553: CPP Slides All

ScenarioManipulate list of heterogeneous objects with common base class

Example: a list of graphical shapes to be drawn// what we would likefor (int i = 0; i < n; ++i) {

A[i].Draw();}

Manipulate list of heterogeneous objects with common base class

Example: a list of graphical shapes to be drawn// what we would likefor (int i = 0; i < n; ++i) {

A[i].Draw();}

Need Draw() to be a virtual function

Placeholder in the Shape class with specialized definitions in the derived class

In C++ we can come close

Page 554: CPP Slides All

Virtual FunctionsFor virtual functions

It is the type of object to which the pointer refers that determines which function is invoked

TriangleShape T(W, P, Red, 1);RectangleShape R(W,P, Yellow, 3, 2);CircleShape C(W, P, Yellow, 4);

Shape *A[3] = {&T, &R, &C};

for (int i = 0; i < 3; ++i) {A[i]->Draw();

} When i is 0, a TriangleShape’s Draw() is used

Page 555: CPP Slides All

Virtual FunctionsFor virtual functions

It is the type of object to which the pointer refers that determines which function is invoked

TriangleShape T(W, P, Red, 1);RectangleShape R(W,P, Yellow, 3, 2);CircleShape C(W, P, Yellow, 4);

Shape *A[3] = {&T, &R, &C};

for (int i = 0; i < 3; ++i) {A[i]->Draw();

} When i is 1, a RectangleShape’s Draw() is used

Page 556: CPP Slides All

Virtual FunctionsFor virtual functions

It is the type of object to which the pointer refers that determines which function is invoked

TriangleShape T(W, P, Red, 1);RectangleShape R(W,P, Yellow, 3, 2);CircleShape C(W, P, Yellow, 4);

Shape *A[3] = {&T, &R, &C};

for (int i = 0; i < 3; ++i) {A[i]->Draw();

} When i is 2, a CircleShape’s Draw() is used

Page 557: CPP Slides All

A Shape Class with a Virtual Draw

class Shape : public WindowObject {public:

Shape(SimpleWindow &w, const Position &p,const color c = Red);color GetColor() const;void SetColor(const color c);virtual void Draw(); // virtual

function!private:

color Color;};

Page 558: CPP Slides All

Virtual FunctionsCan be invoked via either a dereferenced pointer or a reference object

Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed

Can be invoked via either a dereferenced pointer or a reference object

Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed

Definition of the derived function overrides the definition of the base class version

Can be invoked via either a dereferenced pointer or a reference object

Actual function to be invoked is determined from the type of object that is stored at the memory location being accessed

Definition of the derived function overrides the definition of the base class version

Determination of which virtual function to use cannot always be made at compile time

Decision is deferred by the compiler to run time Introduces overhead

Page 559: CPP Slides All

Pure Virtual FunctionHas no implementationHas no implementation

A pure virtual function is specified in C++ by assigning the function the null address within its class definition

Has no implementation

A pure virtual function is specified in C++ by assigning the function the null address within its class definition

A class with a pure virtual function is an abstract base class

Convenient for defining interfaces Base class cannot be directly instantiated

Page 560: CPP Slides All

A Shape Abstract Base Classclass Shape : public WindowObject {

public:Shape(SimpleWindow &w, const Position &p,const color &c = Red);color GetColor() const;void SetColor(const color &c);virtual void Draw() = 0; // pure virtual // function!

private:color Color;

};