acrobat distiller, job 34 - cs.virginia.edu+programdesign/slides/pdf/slides-all.pdf · ability to...

280
1 Basics Machine, software, and program design JPC and JWD © 2002 McGraw-Hill, Inc. Computer Organization CPU - central processing unit Memory Input devices Output devices CPU - central processing unit Where decisions are made, computations are performed, and input/output requests are delegated Memory 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

Upload: vanhuong

Post on 04-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

1

Basics

Machine, software, and program design

JPC and JWD © 2002 McGraw-Hill, Inc.

Computer Organization

CPU - central processing unit

Memory

Input devices

Output devices

CPU - central processing unitWhere decisions are made, computations are performed, and input/output requests are delegated

MemoryStores information being processed by the CPU

Input devicesAllows people to supply information to computers

Output devicesAllows people to receive information from computers

2

Computer Organization

Memory

CPU

InputDevices

OutputDevices

CPU

Brains of the computerArithmetic calculations are performed using the Arithmetic/Logical Unit or ALUControl unit decodes and executes instructions

Arithmetic operations are performed using binary number system

3

Control Unit

The 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

Input and Output Devices

Accessories that allow computer to perform specific tasksReceive information for processingReturn the results of processingStore information

Accessories that allow computer to perform specific tasksReceive information for processingReturn the results of processingStore information

Common input and output devicesSpeakers Mouse ScannerPrinter Joystick CD-ROMKeyboard Microphone DVD

Accessories that allow computer to perform specific tasksReceive information for processingReturn the results of processingStore information

Common input and output devicesSpeakers Mouse ScannerPrinter Joystick CD-ROMKeyboard Microphone DVD

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

units

4

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 480Many cards supportresolution of 1280 by1024 or betterNumber of colors supported varies from 16 to billions

1280pixelsacrossscreen

1024pixelsdown

screen

Application softwarePrograms designed to perform specific tasks that are transparent to the user

System softwarePrograms that support the execution and development of other programsTwo major types

Operating systemsTranslation systems

Software

5

Application Software

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

Common application softwareWord processorsDesktop publishing programsSpreadsheetsPresentation managersDrawing programs

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

Common application softwareWord processorsDesktop publishing programsSpreadsheetsPresentation managersDrawing programs

Learning how to develop application software is our focus

ExamplesWindows®, UNIX®, Mac OS X®

Controls and manages the computing resources

Important services that an operating system providesFile system

Directories, folders, filesCommands that allow for manipulation of the file system

Sort, delete, copyAbility to perform input and output on a variety of devicesManagement of the running systems

Operating System

6

Translation System

Set of programs used to develop software

A key component of a translation system is a translator

Some types of translatorsCompiler

Converts from one language to anotherLinker

Combines resources

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

Performs compilation, linking, and other activities.

Software Development Activities

Editing

Compiling

Linking with precompiled filesObject filesLibrary modules

Loading and executing

Viewing the behavior of the program

7

Software Development Cycle

Compile

Link

Library routines

Other object filesThink

Edit

Load

Execute

Source Program

IDEs

Integrated Development Environments or IDEsSupports the entire software development cycle

E.g., MS Visual C++, Borland, Code Warrior

Provides all the capabilities for developing softwareEditorCompilerLinkerLoaderDebuggerViewer

8

Engineering Software

Software engineeringArea of computer science concerned with building large software systems

ChallengeTremendous advances in hardware have not been accompanied by comparable advances in software

Complexity Trade-off

System complexity tends to grow as the system becomes more user friendly

High

Low

Complexity

Total SoftwareComplexity

User Simplicity

9

Software Engineering Goals

Reliability

Understandability

Cost Effectiveness

Adaptability

Reusability

ReliabilityAn unreliable life-critical system can be fatal

UnderstandabilityFuture development is difficult if software is hard to understand

Cost EffectivenessCost to develop and maintain should not exceed profit

AdaptabilitySystem that is adaptive is easier to alter and expand

ReusabilityImproves reliability, maintainability, and profitability

AbstractionExtract the relevant properties while ignoring inessentials

EncapsulationHide and protect essential information through a controlled interface

Modularity

Hierarchy

AbstractionExtract the relevant properties while ignoring inessentials

EncapsulationHide and protect essential information through a controlled interface

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

Hierarchy

AbstractionExtract the relevant properties while ignoring inessentials

EncapsulationHide and protect essential information through a controlled interface

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

HierarchyRanking or ordering of objects based on some relationship between them

Software Engineering PrinciplesAbstraction

Encapsulation

Modularity

Hierarchy

AbstractionExtract the relevant properties while ignoring inessentials

Encapsulation

Modularity

Hierarchy

10

Extract the relevant object properties while ignoring inessentialsDefines a view of the object

Example - carCar dealer views a car from selling features standpoint

Price, length of warranty, color, …

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

Abstraction

Price? Oil change?

EncapsulationSteps

Decompose an object into partsHide and protect essential informationSupply 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 radioInterface consists of controlsand power and antenna connectors

The details of how it works is hiddenTo install and use a radio

Do not need to know anything about the radio’s electronics

11

Modularity

Dividing 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 systemRadiator Thermostat Water pump

Ignition systemBattery Starter Spark plugs

HierarchyHierarchy

Ranking or ordering of objects based on some relationship between them

Help us understand complex systemsExample - 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

12

Northern Timber Wolf TaxonomyKingdom Animalia

Phylum Chordata

Class Mammalia

Order Carnivora

Family Caninae

Genus Canis

Species Canis lupus

Subspecies Canis lupus occidentalis Northern Timber Wolf

OO Design and Programming

Object-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 televisionThe remote is a physical object withproperties

Weight, size, can send messageto the television

The television is also a physical objectwith various properties

13

ObjectsAn object is almost anything with the following characteristics

Name

Properties

The ability to act upon receiving a messageBasic message types

Directive to perform an actionRequest to change one of its properties

The individual digits of a binary number are referred to as bitsEach 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

14

Binary Arithmetic

5× 315

Equivalent decimal multiplication

0101× 0011

01010101

00000000 0001111

Binary multiplication

Two’s Complement

Representation for signed binary numbers

Leading bit is a sign bitBinary number with leading 0 is positiveBinary number with leading 1 is negative

Magnitude of positive numbers is just the binary representation

Magnitude of negative numbers is found byComplement the bitsReplace all the 1's with 0's, and all the 0's with 1'sAdd one to the complemented number

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

15

Two’s Complement

Performing 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

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+ 11001100001

00001 Is the five-bit result

Throw away the high-order

carry as we are using a five bit representation

16

Fundamentals of C++

Basic programming elements and concepts

JPC and JWD © 2002 McGraw-Hill, Inc.

Program statementDefinitionDeclarationAction

Executable unitNamed set of program statementsDifferent languages refer to executable units by different names

Subroutine: Fortran and BasicProcedure: PascalFunction : C++

Program Organization

17

Program Organization

C++ programCollection of definitions, declarations and functionsCollection can span multiple files

AdvantagesStructured into small understandable unitsComplexity is reducedOverall program size decreases

Object

Object is a representation of some informationNameValues or properties

Data membersAbility to react to requests (messages)!!

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

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

18

// 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

Greeting Output

19

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;

}

Visual C++ IDE with Area.cpp

20

Area.cpp Output

CommentsAllow prose or commentary to be included in programImportance

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

C++ has two conventions for comments// single line comment (preferred)/* long comment */ (save for debugging)

Typical usesIdentify program and who wrote itRecord when program was writtenAdd descriptions of modifications

21

Fundamental C++ Objects

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

Integer objectsFloating-point objectsCharacter objects

11.28345

Z5

P 3.14

Integer Object Types

The basic integer object type is intThe size of an int depends on the machine and the compiler

On PCs it is normally 16 or 32 bitsOther integers object types

short: typically uses less bitslong: typically uses more bits

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

22

Integer Constants

Integer constants are positive or negative whole numbersInteger constant forms

DecimalOctal (base 8)

Digits 0, 1, 2, 3, 4, 5, 6, 7Hexadecimal (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

Consider31 oct and 25 dec

Decimal Constants

Examples9740000L 5000023a (illegal)

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

L or l indicates long integer

23

Character Object Types

Character 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

Character Operations

Arithmetic and relational operations are defined for characters types

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

24

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

Literal String Constants

A 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

25

Floating-Point Object Types

Floating-point object types represent real numbersInteger partFractional part

The number 108.1517 breaks down into the following parts108 - integer part1517 - fractional part

C++ provides three floating-point object typesfloat

double

long double

Floating-Point Constants

Standard decimal notation134.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

26

Names

Used to denote program values or components

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

A name cannot start with a digitUnderscores

A name should not normally start with an underscore

Names are case sensitiveMyObject is a different name than MYOBJECT

There are two kinds of namesKeywordsIdentifiers

Keywords

Keywords are words reserved as part of the languageint, 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

27

Identifiers

Identifiers 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 understandableWhen using multiple word identifiers capitalize the first letter of each word

ExamplesMin

Temperature

CameraAngle

CurrentNbrPoints

Definitions

All objects that are used in a program must be defined

An object definition specifiesTypeName

General definition form

Our convention is one definition per statement!

Type Id, Id, ..., Id;

Knowntype

List of one ormore identifiers

28

Examples

char 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)

Arithmetic Operators

CommonAddition +Subtraction -Multiplication *Division /Mod %

NoteNo exponentiation operatorSingle division operatorOperators are overloaded to work with more than one type of object

Write m*x + bnot mx + b

29

Integer Division

Integer division produces an integer resultTruncates the result

Examples3 / 2 evaluates to 14 / 6 evaluates to 010 / 3 evaluates to 3

Mod

Produces the remainder of the division

Examples5 % 2 evaluates to 112 % 4 evaluates to 04 % 5 evaluates to 4

30

Operators and Precedence

Consider 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 expressions

Standard 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

Operator Precedence

Examples20 - 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)

31

Defining and Initializing

When 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 timeException is when the next statement is an extraction for the object

Remember our convention of one definition per statement!

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;

32

Modifying Objects

Operators and Expressions

JPC and JWD © 2002 McGraw-Hill, Inc.

Memory Depiction

float y = 12.5;12.5y

1001100210031004

33

Memory Depiction

float y = 12.5;

int Temperature = 32;12.5

32

y

Temperature

100110021003100410051006

Memory Depiction

float y = 12.5;

int Temperature = 32;

char Letter = 'c';

12.5

32

'c'

y

Temperature

Letter

1001100210031004100510061007

34

Memory Depiction

float y = 12.5;

int Temperature = 32;

char Letter = 'c';

int Number;

12.5

32

'c'

y

Temperature

Letter

1001100210031004100510061007

-Number 10081009

Assignment Statement

Basic formobject = expression ;

Celsius = (Fahrenheit - 32) * 5 / 9;

y = m * x + b;

ActionExpression is evaluatedExpression value stored in object

Target becomes source

35

Definition

int NewStudents = 6; 6NewStudents

Definition

int NewStudents = 6;

int OldStudents = 21;

6

21

NewStudents

OldStudents

36

Definition

int NewStudents = 6;

int OldStudents = 21;

int TotalStudents;

6

21

NewStudents

OldStudents

-TotalStudents

Assignment Statement

int NewStudents = 6;

int OldStudents = 21;

int TotalStudents;

TotalStudents = NewStudents + OldStudents;

6

21

NewStudents

OldStudents

?TotalStudents

37

Assignment Statement

int NewStudents = 6;

int OldStudents = 21;

int TotalStudents;

TotalStudents = NewStudents + OldStudents;

6

21

NewStudents

OldStudents

27TotalStudents

Assignment Statement

int NewStudents = 6;

int OldStudents = 21;

int TotalStudents;

TotalStudents = NewStudents + OldStudents;

OldStudents = TotalStudents;

6

?

NewStudents

OldStudents

27TotalStudents

38

Assignment Statement

int NewStudents = 6;

int OldStudents = 21;

int TotalStudents;

TotalStudents = NewStudents + OldStudents;

OldStudents = TotalStudents;

6

27

NewStudents

OldStudents

27TotalStudents

Consider

int Value1 = 10; 10Value1

39

Consider

int Value1 = 10;

int Value2 = 20;

10

20

Value1

Value2

Consider

int Value1 = 10;

int Value2 = 20;

int Hold = Value1;

10

20

Value1

Value2

10Hold

40

Consider

int Value1 = 10;

int Value2 = 20;

int Hold = Value1;

Value1 = Value2;

?

20

Value1

Value2

10Hold

Consider

int Value1 = 10;

int Value2 = 20;

int Hold = Value1;

Value1 = Value2;

20

20

Value1

Value2

10Hold

41

Consider

int Value1 = 10;

int Value2 = 20;

int Hold = Value1;

Value1 = Value2;

Value2 = Hold;

20

?

Value1

Value2

10Hold

Consider

int 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

42

Incrementing

int i = 1;i 1

Incrementing

int i = 1;

i = i + 1;

Assign the value of expression i + 1 to i

Evaluates to 2

i 1

2i

43

Const Definitions

Modifier const indicates that an object cannot be changedObject 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 programconst int SampleSize = 100;

Makes changing the constant easyOnly need to change the definition and recompile

Assignment Conversions

Floating-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;

44

Nonfundamental Types

Nonfundamental as they are additions to the language

C++ permits definition of new types and classesA class is a special kind of type

Class objects typically haveData members that represent attributes and valuesMember functions for object inspection and manipulationMembers are accessed using the selection operator (.)

j = s.size();

Auxiliary functions for other behaviors

Libraries often provide special-purpose types and classes

Programmers can also define their own types and classes

Examples

Standard Template Library (STL) provides class string

EzWindows library provides several graphical types and classesSimpleWindow is a class for creating and manipulating

window objectsRectangleShape is a class for creating and manipulating

rectangle objects

45

Class string

Class stringUsed to represent a sequence of characters as a single object

Some definitionsstring Name = "Joanne";

string DecimalPoint = ".";

string empty = "";

string copy = name;

string Question = '?'; // illegal

Nonfundamental Types

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

#include <string>

The using statement makes syntax less clumsyWithout itstd::string s = "Sharp";

std::string t = "Spiffy";

With itusing namespace std; // std contains string

string s = "Sharp";

string t = "Spiffy";

46

EzWindows Library Objects

Definitions 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

ExampleW.Open();

Initialization

Class 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 attributeWindow banner

Second attributeWidth of window in centimeters

Third attributeHeight of window in centimeters

47

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;

}

An EzWindows Project File

48

An EzWindows Project File

Sample Display Behavior

49

RectangleShape Objects

EzWindows 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 SimpleWindowOffsets are measured in centimeters from rectangle center

Width in centimeters

Height in centimeters

Colorcolor is an EzWindows type

RectangleShape Objects

ExamplesSimpleWindow 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);

50

RectangleShape Objects

Some 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

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;

}

51

Sample Display Behavior

Compound Assignment

C++ 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;

52

Increment and Decrement

C++ has special operators for incrementing or decrementing an object by oneExamplesint k = 4;++k; // k is 5

k++; // 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;

Class string

Some 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"); // 10

int k = Saying.find("its"); // ?

53

Class string

Auxiliary 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 do

Response is "Want what you do"

Class string

Auxiliary operators

+ string concatenationstring Part1 = "Me";

string Part2 = " and ";

string Part3 = "You";

string All = Part1 + Part2 + Part3;

+= compound concatenation assignmentstring ThePlace = "Brooklyn";

ThePlace += ", NY";

54

#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;

}

55

If Control Construct

A mechanism for deciding whether an action should be taken

JPC and JWD © 2002 McGraw-Hill, Inc.

Boolean Algebra

Logical expressions have the one of two values - true or falseA rectangle has three sidesThe instructor has a pleasant smile

The branch of mathematics is called Boolean algebraDeveloped by the British mathematician George Boole in the 19th century

Three key logical operatorsAndOrNot

56

Boolean Algebra

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

Example

P Q P and Q

False False FalseFalse True FalseTrue False FalseTrue True True

Boolean Algebra

Or truth table

P Q P or Q

False False FalseFalse True TrueTrue False TrueTrue True True

57

Boolean Algebra

Not truth table

P not P

False TrueTrue False

Boolean Algebra

Can create complex logical expressions by combining simple logical expressions

Examplenot (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

58

A Boolean Type

C++ contains a type named bool

Type bool has two symbolic constantstrue

false

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

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

A Boolean Type

Example logical expressions

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

59

Relational Operators

Equality operators==

!=

Examplesint i = 32;

int k = 45;

bool q = (i == k);

bool r = (i != k);

Relational Operators

Ordering operators<

>

>=

<=

Examplesint i = 5;

int k = 12;

bool p = (i < 10);

bool q = (k > i);

bool r = (i >= k);

bool s = (k <= 12);

60

Operator Precedence Revisited

Precedence of operators (from highest to lowest)

ParenthesesUnary operatorsMultiplicative operatorsAdditive operatorsRelational orderingRelational equalityLogical andLogical orAssignment

Operator Precedence Revisited

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

61

Operator Precedence Revisited

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

Yuck! Do not write expressions like this!

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

62

Conditional Constructs

ProvideAbility to control whether a statement list is executed

Two constructs

If statementifif-elseif-else-ef

Switch statementLeft for reading

The Basic If Statement

Syntaxif (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

63

Example

if (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

Sorting Two Numbers

cout << "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;

64

Semantics

value2 < 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

What is the Output?

int m = 5;

int n = 10;

if (m < n)

++m;

++n;

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

65

The If-Else StatementSyntax

if (Expression)Action1

elseAction2

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

Finding the Max

cout << "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;

66

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

Selection

It is often the case that depending upon the value of an expression we want to perform a particular action

Two major ways of accomplishing this choice

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

Switch statementAn advanced construct

67

An If-Else-If Statement

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

}

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

}

else {cout << nbr << " is zero" << endl;

}

A Switch Statement

switch (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;

}

68

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;

}

69

Iterative Constructs

Mechanisms for deciding under what conditions an action should be repeated

JPC and JWD © 2002 McGraw-Hill, Inc.

Averaging

70

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 itYes, 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 itYes, but it would be gruesome without the use of iteration

C++ Iterative Constructs

Three constructswhile statementfor statementdo-while statement

71

While Syntax

Logical expression that determineswhether the action is to be executed

while ( Expression ) Action

Action to be iterativelyperformed until logical

expression is false

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 with

next statement

72

Computing an Average

int 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;

Execution Trace

int 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

73

Execution Trace

int 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

Execution Trace

int 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

0

0

74

Execution Trace

int 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

0

0

Execution Trace

int 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

0

0

--

75

Execution Trace

int 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

0

0

1

Execution Trace

int 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

0

0

1

1

76

Execution Trace

int 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

0

1

1

1

Execution Trace

int 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

1

1

1

77

Execution Trace

int 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

1

1

--

Execution Trace

int 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

1

1

5

78

Execution Trace

int 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

1

1

5

6

Execution Trace

int 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

1

6

5

2

79

Execution Trace

int 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

2

6

5

6

Execution Trace

int 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

2

6

--

2

80

Execution Trace

int 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

2

6

3

2

Execution Trace

int 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

2

6

3

9

81

Execution Trace

int 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

2

9

3

3

Execution Trace

int 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

3

9

3

3

82

Execution Trace

int 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

3

9

--

3

Execution Trace

int 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

3

9

1

3

83

Execution Trace

int 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

3

9

1

10

Execution Trace

int 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

3

10

1

4

84

Execution Trace

int 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

3

10

1

4

Execution Trace

int 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

3

10

average 2.5

4

85

Execution Trace

int 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

3

10

2.5

4

Execution Trace

int 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

86

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;

}

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

87

Even Better Way of Averagingint 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;

}

The For Statement

Syntaxfor (ForInit ; ForExpression; PostExpression)

Action

Examplefor (int i = 0; i < 3; ++i) {

cout << "i is " << i << endl;

}

88

ForExpr

Action

true false

ForInit

PostExpr

Evaluated onceat the beginning

of the forstatements's

executionThe ForExpr is

evaluated 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

Execution Trace

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

}

cout << "all done" << endl;

i 0

89

Execution Trace

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

}

cout << "all done" << endl;

i 0

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i 0

90

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i 0

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i 1

91

Execution Trace

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

}

cout << "all done" << endl;

i 1

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i 1

92

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i 1

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i 2

93

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i 2

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i is 2

i 2

94

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i is 2

i 2

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i is 2

i 3

95

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i is 2

i 3

Execution Trace

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

}

cout << "all done" << endl;

i is 0

i is 1

i is 2

all done

i 3

96

Table Revisiting

const 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;

}

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!

97

Displaying a Diagonal

SimpleWindow 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();

}

Sample Display

98

Displaying Three Diagonals

SimpleWindow 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.

Sample Display

99

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;

For Into While

ObservationThe for statement is equivalent to{

ForInit;

while (ForExpression) {

Action;

PostExpression;

}

}

100

Counting Characters

int 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

Counting All Characters

char 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

101

#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

Iteration Do’s

Key PointsMake 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 performedHave a clear purpose for the loop

Document the purpose of the loopDocument how the body of the loop advances the purpose of the loop

102

The Do-While Statement

Syntaxdo Actionwhile (Expression)

SemanticsExecute ActionIf Expression is true then execute Action againRepeat this process until Expression evaluates to false

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

Action

true

false

Expression

Waiting for a Proper Reply

char Reply;

do {

cout << "Decision (y, n): ";

if (cin >> Reply)

Reply = tolower(Reply);

else

Reply = 'n';

} while ((Reply != 'y') && (Reply != 'n'));

103

Libraries

Computational assistants

JPC and JWD © 2002 McGraw-Hill, Inc.

Previous examples

Programmer-defined functionsmain()

ApiMain()

Library-defined functionscin.get()

string member functions size()RectangleShape member function Draw()SimpleWindow member function Open()

AdviceDon’t reinvent the wheel! There are lots of libraries out there

Functions

104

Terminology

A function is invoked by a function call / function invocation

y = f(a);

Terminology

A function call specifiesThe function name

The name indicates what function is to be called

y = f(a);

A function call specifiesThe function name

The name indicates what function is to be called

y = f(a);

The actual parameters to be used in the invocationThe values are the information that the called function requires from the invoking function to do its task

y = f(a);

105

Terminology

A function call produces a return valueThe return value is the value of the function call

y = f(a);

Invocation Process

Flow 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;

}

106

Invocation Process

Flow 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;

}

Invocation Process

Flow 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;

}

107

Invocation Process

Flow 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;

}

Invocation Process

Flow 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;

}

108

Execution Process

Function 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 ofthe invocation expression

Function Prototypes

Before a function can appear in an invocation its interface mustbe 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

109

Function Prototypes

Before a function can appear in an invocation its interface mustbe 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

Libraries

LibraryCollection of functions, classes, and objects grouped by commonality of purposeInclude statement provides access to the names and descriptions of the library componentsLinker connects program to actual library definitions

Previous examplesString: STL’s string classGraphics: EzWindows

110

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

Some Standard Libraries

fstreamFile stream processing

assertC-based library for assertion processing

iomanipFormatted input/output (I/O) requests

ctypeC-based library for character manipulations

mathC-based library for trigonometric and logarithmic functions

NoteC++ has many other libraries

111

Library Header Files

Describes library components

Typically containsFunction prototypes

Interface descriptionClass definitions

Sometimes containsObject definitions

Example: cout and cin in iostream

Library Header Files

Typically do not contain function definitionsDefinitions are in source filesAccess to compiled versions of source files provided by a linker

112

#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

#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;

}}

113

ifstream sin("in1.txt"); // extract from in1.txt

ofstream sout("out1.txt"); // insert to out1.txt

string s;

while (sin >> s) {

sout << s << endl;

}

sin.close(); // done with in1.txt

sout.close(); // done with out1.txt

sin.open("in2.txt"); // now extract from in2.txt

sout.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.txt

sout.close(); // done with out2.txt

114

Programmer-defined Functions

Development of simple functions using value and reference parameters

JPC and JWD © 2002 McGraw-Hill, Inc.

Includes description of the interface and the function bodyInterface

Similar to a function prototype, but parameters’ names are required

BodyStatement list with curly braces that comprises its actionsReturn statement to indicate value of invocation

Function Definition

115

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

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

116

Simple Programs

Single fileInclude statementsUsing statementsFunction prototypesFunction definitions

Single fileInclude statementsUsing statementsFunction prototypesFunction definitions

Functions use value parameter passingAlso known as pass by value or call by value

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

#include <iostream>

using namespace std;

float CircleArea(float r);

// main(): manage circle computation

int 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 circle

float CircleArea(float r) {

const float Pi = 3.1415;

return Pi * r * r;

}

117

Value Parameter Rules

Formal 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 thecurrent 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

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

118

PromptAndRead()

// PromptAndRead(): prompt and extract next

// integer

int PromptAndRead() {

cout << "Enter number (integer): ";

int Response;

cin >> Response;

return Response;

}

Sum()

// Sum(): compute sum of integers in a ... b

int Sum(int a, int b) {

int Total = 0;

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

Total += i;

}

return Total;

}

119

Problem

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

DesignPrompt user and read the first numberPrompt user and read the second numberCalculate the sum of integers in the range smaller...larger by adding in turn each integer in that rangeDisplay the sum

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;

}

120

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

int PromptAndRead() {

cout << "Enter number (integer): ";

int Response;

cin >> Response;

return Response;

}

// Sum(): compute sum of integers in a ... b

int Sum(int a, int b) {

int Total = 0;

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

Total += i;

}

return Total;

}

A block is a list of statements within curly braces

Blocks can be put anywhere a statement can be put

Blocks within blocks are nested blocks

An object name is known only within the block in which it is defined and in nested blocks of that block

A parameter can be considered to be defined at the beginning of the block corresponding to the function body

Blocks and Local Scope

A block is a list of statements within curly braces

121

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

}

Name Reuse

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

122

However, Don’t Do This At Homevoid 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

}

Global Scope

Objects 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 objectsExceptions tend to be important constants

Global objects with appropriate declarations can even be used inother 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 nameUnary scope operator :: can provide access to global object even if name reuse has occurred

123

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;

}

Consider

int main() {

int Number1 = PromptAndRead();

int Number2 = PromptAndRead();

if (Number1 > Number2) {

Swap(Number1, Number2);

}

cout << "The numbers in sorted order:"

<< Number1 << ", " << Number2 << endl;

return 0;

}

124

Using

void Swap(int a, int b) {

int Temp = a;

a = b;

b = Temp;

return;

}

Doesn’t do what we want!

125

Consider

A parameter passing style whereChanges to the formal parameter change the actual parameter

That would work!

126

Reference Parameters

If the formal argument declaration is a reference parameter then

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

Function definition determines whether a parameter’s passing style is by value or by reference

Reference parameter formptypei &pnamei

void Swap(int &a, int &b)

Reconsider

int main() {

int Number1 = PromptAndRead();

int Number2 = PromptAndRead();

if (Number1 > Number2) {

Swap(Number1, Number2);

}

cout << "The numbers in sorted order: "

<< Number1 << ", " << Number2 << endl;

return 0;

}

127

Using

void 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

Consider

int 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;

}

128

Extraction

Function 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?

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;

}

129

Constant Parameters

The const modifier can be applied to formal parameter declarationsconst indicates that the function may not modify the parametervoid 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): ");

Constant Parameters

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

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

QuestionWhy not just pass the object by value?

Answer?

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

QuestionWhy not just pass the object by value?

AnswerFor large objects, making a copy of the object can be very inefficient

130

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;

}

Default Parameters

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

ObservationsOur functions up to this point required that we explicitly pass a value for each of the function parametersIt would be convenient to define functions that accept a varying number of parameters

ObservationsOur functions up to this point required that we explicitly pass a value for each of the function parametersIt would be convenient to define functions that accept a varying number of parameters

Default parametersAllows programmer to define a default behavior

A value for a parameter can be implicitly passedReduces need for similar functions that differ only in the number of parameters accepted

131

Default Parameters

If the formal argument declaration is of the form

ptypei pnamei = dvaluei

thenIf there is no ith argument in the function invocation, pnamei is initialized to dvalueiThe parameter pnamei is an optional value parameter

Optional reference parameters are also permitted

Consider

void 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();

132

Default Parameters

Default parameters must appear after any mandatory parameters

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

...

}

Cannot come before mandatory parameters

Default Parameters

Considerbool 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!

133

Function Overloading

A function name can be overloadedTwo functions with the same name but with different interfaces

Typically this means different formal parameter listsDifference in number of parametersMin(a, b, c)

Min(a, b)

Difference in types of parametersMin(10, 20)

Min(4.4, 9.2)

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;}

134

Function Overloading

int 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;

}

Function Overloading

Compiler uses function overload resolution to call the most appropriate function

First looks for a function definition where the formal and actual parameters exactly matchIf 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

AdviceBe very careful when using this feature

135

Random Numbers

Generating a sequence of random numbers is often useful In a game, it ensures that a player does not seethe same behavior each timeIn a simulation of a complex system,random numbers can be used tohelp generate random events

Car crash in a simulationof a highway systemLikelihood of a gene in cell mutationWeather simulation

Uniform Random Numbers

Uniform random number sequenceA sequence of random numbers where

Each value in the sequence is drawn from the same range of numbersIn each position of the sequence, any value in the number range is equally likely to occur

136

Random Numbers

ExamplesGenerate a uniform randomnumber sequence in the range1 to 6

Use a fair six-sided dieEach roll represents a new random number

Generate a uniform random numbersequence in the range 1 to 2

Use a fair coinHeads: 1, Tails: 2

Random Numbers

We 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 randomThey are properly called pseudorandom numbers

30 21 9 28 29 ...

137

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;

}

Different Sequences

To 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;

}

138

Different Sequences

To 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 usedReturns an integral value of type time_tInvocation time(0) returns a suitable value for generating a random sequence

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;

}

139

Class Construct

Defining objects with attributes and behavior

JPC and JWD © 2002 McGraw-Hill, Inc.

Class Types

Class constructAllows 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 constructAllows 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 isRectangleShape

140

Terminology

ClientProgram using a class

Object behaviorsRealized in C++ via member functions (methods)

Object attributesAre known as data members in C++

ClientProgram using a class

Object behaviorsRealized in C++ via member functions (methods)

RectangleShapes can be drawn or resized

Object attributesAre known as data members in C++

ClientProgram using a class

Object behaviorsRealized in C++ via member functions (methods)

RectangleShapes can be drawn or resized

Object attributesAre known as data members in C++

RectangleShapes have width, height, position, color

Member Functions

Provide a controlled interface to data members and object access and manipulation

Create objects of the classInspect, mutate, and manipulate object of the classCan be used to keep data members in a correct state

SetSize()SetColor()Draw()

141

Member Functions

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

FactoidConstructors do not have a type

Considered superfluous

Member Functions

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

ExampleRectangleShapes have an inspector GetColor()

color CurrColor = R.GetColor();

142

Member Functions

MutatorsChanges the value of an attribute

ExampleRectangleShapes have a mutator SetColor()

R.SetColor(Black);

Member Functions

FacilitatorsCauses an object to perform some action or service

ExampleRectangleShapes have a facilitator Draw()

R.Draw();

143

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 missingDefault constructor parametersMember function

Erase()Inherited member functions

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

#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();

SimpleRectangleShapeHeader 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

144

// 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

// 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

145

private:

// data members

SimpleWindow &Window;

float thisXCenter;

float thisYCenter;

color thisColor;

float thisWidth;

float thisHeight;

};

#endif

Simple RectangleShape

A client cannot directly access either private or protected data members

Access right

Close of #ifndef directive

Access Tests

ConsiderSimpleWindow 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);

146

The RectangleShape Class

Public accessAll clients and class membershave access to the publicmembers

Private accessOnly classmembershave accessto theprivatemembers

Public datamembers and

member functions

Private datamembers and

member functions

Access fromoutside of class

Accessdenied

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

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

Instantiations

C: RectangleShapeDM: 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

147

#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;

}

148

Abstract Data Types

Development and Implementation

JPC and JWD © 2002 McGraw-Hill, Inc.

Our Goal

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

User should not have to bother with unnecessary details

Exampleprogramming a microwave to make popcorn should not require a physics course

149

Golden Rule

Use information hiding and encapsulation to support integrity ofdata

Put implementation details in a separate moduleImplementation details complicate the class declarations

Data members are private so that use of the interface is required

Makes clients generally immune to implementation changes

Another Golden Rule

Keep it simple – class minimality rule

Implement a behavior as a nonmember function when possible

Only add a behavior if it is necessary

150

Abstract Data Type

Well-defined and complete data abstraction using the information-hiding principle

Rational Number Review

Rational numberRatio of two integers: a/b

Numerator over the denominator

Standard operationsAddition Multiplication

Subtraction Division

bdbc+ad=

dc+

ba

bdac=

dc*

ba

ab

- cd

= ad - bcbd bc

ad=dc/

ba

151

Abstract Data Type

ConsiderRational a(1,2); // a = 1/2

Rational b(2,3); // b = 2/3

cout << a << " + " << b << " = " << a + b;

Rational s; // s = 0/1

Rational t; // t = 0/1

cin >> s >> t;cout << s << " * " << t << " = " << s * t;

ObservationNatural look that is analogous to fundamental-type arithmetic objects

Rational Attributes

A numerator and denominatorImplies in part a class representation with two private intdata members

NumeratorValue and DenominatorValue

152

Rational Public Behaviors

Rational arithmeticAddition, subtraction, multiplication, and division

Rational relationalEquality and less than comparisons

Practice rule of class minimality

Rational Public Behaviors

ConstructionDefault construction

Design decision 0/1Specific construction

Allow client to specify numerator and denominator Copy construction

Provided automatically

AssignmentProvided automatically

Insertion and extraction

153

Non-Public Behaviors

Inspection and mutation of data members

Clients deal with a Rational object!

Auxiliary Behaviors

Operations (necessarily public)Arithmetic, relational, insertion, and extraction operations

Provides the natural form we expectClass definition provides a functional form that auxiliary operators use

Provides commutativity consistencyFor C++ reasons 1 + r and r + 1 would not be treated the same if addition was a member operation

154

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);

Library Components

Rational.hClass definitions and library function prototypes

Rational.cppImplementation source code – member and auxiliary function definitions

Auxiliary functions are assisting global functions that provide expected but non-member capabilities

Rational.objTranslated version of Rational.cpp (linkable)

Rational.libLibrary version of Rational.obj that is more readily linkable

155

#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

Compiler translates the unit and produces MyProgram.obj

Compiler 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.exe

Preprocessor combines the definitions and prototypes iniostream and rational headers along with MyProgram.cpp to produce a compilation unit

Compiler must be told where to look for Rational.h

156

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

Rational Header File OverviewFile layout

Class definition and library prototypes nested within preprocessor statements

Ensures one inclusion per translation unitClass definition precedes library prototypes

#ifndef RATIONAL_H#define RATIONAL_H

class Rational {

// …} ;

// library prototypes …#endif

157

Class Rational Overview

class 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

} ;

Rational Public Section

public:

// default constructor

Rational();

// specific constructor

Rational(int numer, int denom = 1);

// arithmetic facilitators

Rational Add(const Rational &r) const;

Rational Multiply(const Rational &r) const;

// stream facilitators

void Insert(ostream &sout) const;

void Extract(istream &sin);

158

Rational Protected Section

protected:

// inspectors

int GetNumerator() const;

int GetDenominator() const;

// mutators

void SetNumerator(int numer);

void SetDenominator(int denom);

Rational Private Section

private:

// data members

int NumeratorValue;

int DenominatorValue;

159

// 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

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 look

Should << be a member?Considerr << cout;

160

Const Power

const Rational OneHalf(1,2);

cout << OneHalf; // legal

cin >> OneHalf; // illegal

Rational Implementation#include <iostream> // Start of rational.cpp

#include <string>

using namespace std;

#include "rational.h"

// default constructor

Rational::Rational() {

SetNumerator(0);

SetDenominator(1);

}

ExampleRational r; // r = 0/1

Which objects arebeing referenced?

Is this necessary?

161

Remember

Every class objectHas its own data members

Has its own member functionsWhen 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

Remember

Auxiliary functionsAre 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

162

Specific Constructor

// (numer, denom) constructor

Rational::Rational(int numer, int denom) {

SetNumerator(numer);

SetDenominator(denom);

}

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

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

Inspectors

int 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?

163

Numerator Mutator

void Rational::SetNumerator(int numer) {

NumeratorValue = numer;

}

Where are the following legal?

SetNumerator(1);

t.SetNumerator(2);

Why no const?

Denominator Mutatorvoid Rational::SetDenominator(int denom) {

if (denom != 0) {

DenominatorValue = denom;

}

else {

cerr << "Illegal denominator: " << denom

<< "using 1" << endl;DenominatorValue = 1;

}

}

ExampleSetDenominator(5);

164

Addition Facilitator

Rational 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);

Multiplication Facilitator

Rational 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);

165

Insertion Facilitator

void Rational::Insert(ostream &sout) const {

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

return;

}

Examplet.Insert(cout);

Why is sout a reference parameter?

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);

166

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;

Auxiliary Insertion Operator

ostream& 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; // unnatural

cout << t << endl; // natural

167

Auxiliary Extraction Operator

// extracting a Rational

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

r.Extract(sin);

return sin;

}

Why a reference return?

We can do either

t.Extract(cin); // unnatural

cin >> t; // natural

What’s Happening Here?

Suppose the following definitions are in effectRational 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

168

Copy Construction

Default copy constructionCopy 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 theexperience

A Rational Copy Constructor

Rational::Rational(const Rational &r) {

int a = r.GetNumerator();

int b = r.GetDenomiator();

SetNumerator(a);

SetDenominator(b);

}

Rational s(a);

Rational t = b;

169

Gang Of Three

If it is appropriate to define a copy constructor thenConsider also defining

Assignment operatorCopy source to target and return target

A = B = CDestructor

Clean up the object when it goes out of scope

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

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

170

Rational Destructor

Rational::~Rational() {

// nothing to do

}

171

Arrays

A Mechanism for representing lists

JPC and JWD © 2002 McGraw-Hill, Inc.

Lists

Problem solving often requires information be viewed as a listList may be one-dimensional or multidimensional

Problem solving often requires information be viewed as a listList may be one-dimensional or multidimensional

C++ provides two list mechanismsArrays

Traditional and important because of legacy librariesRestrictions on its use

Problem solving often requires information be viewed as a listList may be one-dimensional or multidimensional

C++ provides two list mechanismsArrays

Traditional and important because of legacy librariesRestrictions on its use

Container classesFirst-class list representationCommon containers provided by STL

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

172

Lists

AnalogiesEgg cartonApartmentsCassette carrier

Array Terminology

List 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 nameList 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 nameList elements are of the same type — the base typeElements of a list are referenced by subscripting or indexing the common name

173

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++ Restrictions

Subscripts 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.

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

174

Example Definitions

Supposeconst 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 ints

char B[MaxStringSize]; // array of 80 chars

double C[M*N]; // array of 800 floats

int Values[MaxListSize]; // array of 1000 ints

Rational D[N-15]; // array of 5 Rationals

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 indexFirst element of list has index 0

A[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 indexFirst element of list has index 0

A[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 indexFirst element of list has index 0

A[0]

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

Last element has an index one less than the size of the listA[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 indexFirst element of list has index 0

A[0]

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

Last element has an index one less than the size of the listA[9]

Incorrect indexing is a common errorA[10] // does not exist

175

Array Elements

Supposeint 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]

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

Array Element Manipulation

Considerint 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]

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

176

Array Element Manipulation

Considerint 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]

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

Array Element Manipulation

Considerint 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-- -- --

177

Array Element Manipulation

Considerint 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-- -- --

Array Element Manipulation

Considerint 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-- -- --

178

Array Element Manipulation

Considerint 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 --

Array Element Manipulation

Considerint 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 --

179

Extracting Values For A List

int A[MaxListSize];

int n = 0;

int CurrentInput;

while((n < MaxListSize) && (cin >> CurrentInput)){

A[n] = CurrentInput;

++n;

}

Displaying A List

// List A of n elements has already been set

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

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

}

cout << endl;

180

Smallest Value

ProblemFind the smallest value in a list of integers

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

OutputSmallest value in the list

NoteList remains unchanged after finding the smallest value!

Preliminary Design

RealizationsWhen 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

RealizationsWhen looking for value with distinguishing characteristics, need a way of remembering best candidate found so far

Make it a function -- likely to be used oftenDesign

Search array looking for smallest valueUse a loop to consider each element in turnIf 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

181

Necessary Information

Information to be maintainedArray with values to be inspected for smallest valueNumber of values in arrayIndex of current element being consideredSmallest value so far

A More Detailed Design

SolutionFunction that takes array of values and array size as its two in parameters; returns smallest value seen as its valueInitialize smallest value so far to first elementFor 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 currentelement

Return smallest value seen as value of function

182

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?

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

183

Remember

Arrays are always passed by referenceArtifact 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

Some Useful Functions

void 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;

}

}

184

Useful Functions Being Used

const int MaxNumberValues = 25;

int Values[MaxNumberValues];

int NumberValues;

GetList(Values, NumberValues, MaxNumberValues);

DisplayList(Values, NumberValues);

Searching

ProblemDetermine whether a value key is one of the element values

Does it matter ifElement values are not necessarily numbersElement values are not necessarily uniqueElements may have key values and other fields

185

Sequential List Searching

int 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

Example Invocation

cin >> 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;

}

186

Sorting

ProblemArranging elements so that they are ordered according to some desired scheme

Standard is non-decreasing orderWhy don't we say increasing order?

Major tasksComparisons of elementsUpdates or element movement

Common Sorting Techniques

Selection sortOn ith iteration place the ith smallest element in the ith list location

Bubble sortIteratively 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

187

Common Sorting Techniques

Insertion sortOn ith iteration place the ith element with respect to the i-1 previous elements

In text

Quick sortDivide 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

SelectionSort

void 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]);

}

}

188

Complexity

SelectionSort() QuestionHow long does the function take to run

Proportional to n*n time units, where n is the number of elements in the list

General questionHow fast can we sort using the perfect comparison-based method

The best possible worst case time is proportional ton log n time units

189

Vectors

First-class mechanism for representing lists

JPC and JWD © 2002 McGraw-Hill, Inc.

Standard Template Library

What 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 mechanismHave we seen this library before?

String class is part of the STL

190

Sequencesdeque, list, and vector

Vector supports efficient random-access to elements

STL Container Classes

Associativemap, set

Adapterspriority_queue, queue, and stack

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

191

Example#include <vector>

#include <iostream>

using namespace std;

int main() {

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

A.resize(8, 2); // A: 0 0 0 0 2 2 2 2

vector<int> B(3, 1); // B: 1 1 1

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

A[i] = B[i] + 2;

} // A: 3 3 3 0 2 2 2 2

A = B; // A: 1 1 1

return 0;

}

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!

192

Construction

Basic construction

vector<T> List;

Examplevector<int> A; // 0 ints

vector<float> B; // 0 floats

vector<Rational> C; // 0 Rationals

Base element type

Container name

Construction

Basic construction

vector<T> List(SizeExpression);

Examplevector<int> A(10); // 10 ints

vector<float> B(20); // 20 floats

vector<Rational> C(5); // 5 Rationals

int n = PromptAndRead();

vector<int> D(n); // n ints

Base element type

Container name

Number of elements to be defaultconstructed

193

Construction

Basic construction

vector<T> List(SizeExpression, Value);

Examplevector<int> A(10, 3); // 10 3s

vector<float> B(20, 0.2); // 20 0.2s

Rational r(2/3);

vector<Rational> C(5, r); // 5 2/3s

Base element type

Container name

Number of elements to be defaultconstructed

Initial value

Vector Interface

size_type size() const

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

bool empty() const

Returns true if there are no elements in the vector; otherwise, it returns false

if (A.empty()) {

// ...

194

Vector Interface

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

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

Shallow copyThe 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

Vector Interface

reference operator [](size_type i)

Returns a reference to element i of the vectorLvalue

const_reference operator [](size_type i) const

Returns a constant reference to element i of the vectorRvalue

195

Example

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

const 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; // lvalue

cout << B[i] << endl; // rvalue

}

Vector Interface

reference 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 iof the vector; otherwise, throws an exception

196

Example

vector<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

Vector Interface

void 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 endAdditions if any are performed at the endNew elements have value val

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

A.resize(8, 2); // A: 0 0 0 0 2 2 2 2

A.resize(3,1); // A: 0 0 0

197

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);

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

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

cout << A[i] << endl;

}

}

cout << "Your numbers: ";

PutList(MyList)

198

Vector Interface

pop_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

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);

199

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;

Vector Interface

reference 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 1

int& val = B.front();

val = 7; // B: 7 1 1 1

200

Vector Interface

reference 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 1

int& val = C.back();

val = 5; // C: 1 1 1 5

Iterators

Iterator is a pointer to an elementReally pointer abstraction

Mechanism for sequentially accessing the elements in the listAlternative to subscripting

There is an iterator type for each kind of vector list

NotesAlgorithm component of STL uses iteratorsCode using iterators rather than subscripting can often be reused by other objects using different container representations

201

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 0

C[0] = 0; C[1] = 1; C[2] = 2; C[3] = 3;

vector<int>::iterator p = C.begin();

vector<int>::iterator q = C.end();

Iterators

To 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 0

iterator p = C.begin();

iterator q = C.end();

202

Iterator Operators

* dereferencing operatorProduces a reference to the object to which the iterator p points

*p

++ point to next element in listIterator p now points to the element that followed the previous element to which p points

++p

-- point to previous element in listIterator p now points to the element that preceded the previous element to which p points

--p

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; // 100

reverse_iterator q = List.rbegin();

cout << *q; // 102

++q;

cout << *q; // 101

--q;

cout << *q; // 102

203

Vector Interface

insert(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

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]);

}

}

204

QuickSort

QuickSortDivide the list into sublists such that every element in the left sublist <= to every element in the right sublistRepeat 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);

}

}

Picking The Pivot Element

void Pivot(vector<char> &A, int left, int right) {

if (A[left] > A[right]) {

Swap(A[left], A[right]);

}

}

205

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;

}

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

206

InsertionSort

void 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

}

Searching Revisited

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

SolutionBinary search

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

207

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

if (a > b){

return b+1;

}

int m = (a + b)/2

if (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

String Class Revisited

void GetWords(vector<string> &List) {

List.resize(0);

string s;

while (cin >> s) {

List.push_back(s);

}

}

208

Using GetWords()

Suppose standard input containsA 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."

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'

209

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

Reconsider A

Wherevector<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."

210

Counting o’s

The 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

Explicit Two-Dimensional List

Consider definitionvector< vector<int> > A;

ThenA 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

211

Multi-Dimensional Arrays

Syntaxbtype mdarray[size_1][size_2] ... [size_k]

Wherek - dimensional arraymdarray: array identifiersize_i: a positive constant expressionbtype: standard type or a previously defined user type and is the base type of the array elements

Semanticsmdarray is an object whose elements are indexed by a sequence of k subscriptsthe i-th subscript is in the range 0 ... size_i - 1

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 memoryThe first row occupies the first portionThe second row occupies the second portion

... ...M[0][0] M[0][3]

-- --M[1][0] M[1][3]

-- --

212

Identity Matrix Initialization

const 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;

}

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 firstbrackets are empty

213

EzWindows API

A Graphical Application Programmer Interface

JPC and JWD © 2002 McGraw-Hill, Inc.

Event-based Programming

Messages are sent to your program by the operating system

Mouse downMouse upKey downKey upRefreshQuitTimer

Handle messages by registering a call back

C: User Program

C: SimpleWindow User start

Mouse click

Timer tick

User end

214

EzWindows Coordinate System

Use centimetersMetricSimpler to understand than pixelsDevice independentHelps 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)

Class Position

For earlier objects, the position was specified by given both anx-coordinate and a y-coordinateWe can now introduce a new object called Position and use it

215

Position

class 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);

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.

216

Class SimpleWindow

Writing text in a window

void 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

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();

217

Hello EzWindows

// Create bounding box for textPosition 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;}

Hello EzWindows// ApiEnd(): shutdown the windowint ApiEnd() {

HelloWindow.Close();

return 0;}

218

Class SimpleWindow

Simple Window constructor

SimpleWindow::SimpleWindow(

const string &t =

"Untitled“

float w = 8,

float h = 8,

const Position &p = Position(0,0)

)

Bitmaps

219

Class BitMap

Uses BitMapStatus

enum BitMapStatus {NoBitMap, BitMapOkay, NoWindow

};

Class BitMap

Class 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

220

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();

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;}

221

Fun with Pictures

Mouse Events

Before we can react to a mouse event in a SimpleWindowMust tell window what function to call when an event occurs

Registering a callback

To register a callback use the SimpleWindow member functionSetMouseClickCallback.

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

222

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;}

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;}

223

Timer Events

The 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

Timer Functions

void SimpleWindow::SetTimerCallback(TimerTickCallbackFunction f)

Registers a callback for a timer tickFunction f() will be called when a timer tick occurs.The function f() must be declared to take no parameters, and it should return an intThe return value of f() indicates whether the event was handled successfullyA value of 1 is to indicate successA value of 0 is to indicate an error occurred

224

Timer Functions

int SimpleWindow::StartTimer(int Interval)

Starts timer runningParameter Interval is the number of milliseconds between timer eventsThe return value indicates whether the timer was successfully startedA return value of 1 indicates successA return value of 0 indicates the timer could not be set up

void SimpleWindow::StopTimer()

Turns timer off

#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

225

Example

int 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;

}

Example

int ApiEnd() {// Stop the timers and close the windowsW1.StopTimer();W1.Close();return 0;

}

226

Pointers and Dynamic Objects

Mechanisms for developing flexible list representations

JPC and JWD © 2002 McGraw-Hill, Inc.

Usefulness

Mechanism 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 objectsObjects 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

227

Categorizing Expressions

Lvalue expressionsRepresent objects that can be evaluated and modified

Rvalue expressionsRepresent objects that can only be evaluated

Considerint a;

vector<int> b(3);

int c[3];

a = 1; // a: lvalue

c[0] = 2*a + b[0]; // c[0], a, b[0]: lvalues

ObservationNot all lvalues are the names of objects

Basics

PointerObject 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

228

Examples of uninitialized pointers

int *iPtr; // iPtr is a pointer to an int

char *s; // s is a pointer to a char

Rational *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 i

char *t = &c; // t is a pointer to a char c

Indicates pointer object

Indicates to take the address of the object

Syntax

Examples of uninitialized pointers

int *iPtr; // iPtr is a pointer to an int

char *s; // s is a pointer to a char

Rational *rPtr; // rPtr is a pointer to a

// Rational

Indicates pointer object

Memory Depiction

int i = 1;

char c = 'y';

int *ptr = &i;

char *t = &c

229

Indirection Operator

An asterisk has two uses with regard to pointers

In a definition, it indicates that the object is a pointer

char *s; // s is of type pointer to char

In expressions, when applied to a pointer it evaluates to the object to which the pointer points

int 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

Address Operator

& use is not limited to definition initialization

int i = 1;

int j = 2;

int *ptr;

ptr = &i; // ptr points to location of i

*ptr = 3; // contents of i are updated

ptr = &j; // ptr points to location of j

*ptr = 4; // contents of j are updated

cout << i << " " << j << endl;

230

Null Address

0 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 null

int *ptr = 0;

cout << *ptr << endl; // invalid, ptr

// does not point to

// a valid int

Member Indirection

Consider

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)

Consider

Rational 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)

231

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.

Constants and Pointers

A constant pointer is a pointer such that we cannot change the location to which the pointer points

char 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 points

char 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 constant

const char *ptr2 = &d;

*ptr2 = 'e'; // illegal: cannot change d

// through indirection with ptr2

232

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 operationDynamic objects can exist beyond the function in which they were allocatedObject 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

Differences

Local objects and parameters

Dynamic object

Operation specifiesThe type and number of objects

If there is sufficient memory to satisfy the requestA pointer to sufficient memory is returned by the operation

If there is insufficient memory to satisfy the requestAn 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 objectsRequested from the free store

Free store is memory controlled by operating system

233

The Basic New Form

SyntaxPtr = new SomeType ;

WherePtr is a pointer of type SomeType

BewareThe newly acquired memory is uninitialized unless there is a default SomeType constructor

Examples

int *iptr = new int;

Rational *rptr = new Rational;

—iptr

Uninitialized int object

0/1rptr

Rational object with defaultinitialization

234

Another Basic New Form

Syntax

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

Examples

int *iptr = new int(10);

Rational *rptr = new Rational(1,2);

10iptr

1/2rptr

235

The Primary New Form

Syntax

P = new SomeType [Expression] ;

WhereP is a pointer of type SomeTypeExpression is the number of contiguous objects of type SomeType to be constructed -- we are making a list

NoteThe newly acquired list is initialized if there is a default SomeType constructor

Because of flexible pointer syntaxP can be considered to be an array

Examples

int *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

236

Right Array For The Job

cout << "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

Delete Operators

Forms of request

delete P; // used if storage came from new

delete [] P; // used if storage came from new[]

Storage pointed to by P is returned to free store

P is now undefined

237

Cleaning Up

int n;

cout << "Enter list size: ";

cin >> n;

int *A = new int[n];

GetList(A, n);

SelectionSort(A, n);

DisplayList(A, n);

delete [] A;

Dangling Pointer Pitfall

int *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

?

238

Memory Leak Pitfall

int *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

A Simple Dynamic List Type

What we want

An integer list data type IntList with the basic features of thevector data type from the Standard Template Library

Features and abilities

True objectCan be passed by value and referenceCan be assigned and copied

Inspect and mutate individual elementsInspect list sizeResize listInsert and extract a list

239

Sample IntList Usage

IntList 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 ]

IntList Definition

class IntList {

public:

// constructors

IntList(int n = 10, int val = 0);

IntList(const int A[], int n);

IntList(const IntList &A);

// destructor

~IntList();

// inspector for size of the list

int size() const;

// assignment operator

IntList & operator=(const IntList &A);

240

IntList Definition (continued)

public:

// inspector for element of constant list

const int& operator[](int i) const;

// inspector/mutator for element of

// nonconstant list

int& operator[](int i);

// resize list

void resize(int n = 0, int val = 0);

// convenience for adding new last element

void push_back(int val);

IntList Definition (continued)

private:

// data members

int *Values; // pointer to elements

int NumberValues; // size of list

};

// IntList auxiliary operators -- nonmembers

ostream& operator<<(ostream &sout, const IntList &A);

istream& operator>>(istream &sin, IntList &A);

241

Default Constructor

IntList::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;

}

}

Gang of Three Rule

If a class has a data member that points to dynamic memory then that class normally needs a class-defined

Copy constructorConstructor that builds an object out of an object of the same type

Member assignment operatorResets an object using another object of the same type as a basis

DestructorAnti-constructor that typically uses delete the operator on the data members that point to dynamic memory

242

Why A Tailored Copy Constructor

Suppose we use the default copy constructorIntList A(3, 1);

IntList B(A);

And thenA[2] = 2;

ThenB[2] is changed!Not what a client would expect

ImplicationMust use tailored copy constructor

A

B

1 2 1

3

3

Tailored Copy Constructor

IntList::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?

243

Gang Of Three

What 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 deletedDefine a destructor

A class object going out of scope automatically has its destructor invoked

IntList::~IntList() {

delete [] Values;

}

Notice the tilde

First Assignment Attempt

Algorithm

Return existing dynamic memory

Acquire sufficient new dynamic memory

Copy the size and the elements of the source object to the target element

244

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;

This Pointer

Considerthis

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;

}

245

Member Assignment OperatorIntList& 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?

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 lvalue

int& IntList::operator[](int i) {

assert((i >= 0) && (i < size()));

return Values[i];

}

246

Stream Operators

Should 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)

Beware of Friends

If a class needs toCan 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);

// ...

};

247

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?

Proper << Implementation

ostream& operator<<(ostream &sout,

const IntList &A){

sout << "[ ";

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

sout << A[i] << " ";

}

sout << "]";

return sout;

}

248

Inheritance

Mechanism for deriving new classes from existing classes

JPC and JWD © 2002 McGraw-Hill, Inc.

Think of a Bicycle

249

Think of a Tandem Bike

Think of a Racing Bike

250

Think of a Mountain Bike

Thinking About Bicycles

A tandem bicycle is a kind of bicycleBicycle with two seats

A mountain bicycle is a kind of bicycle Bicycle with shocks

A racing bicycle is a kind of bicycleLightweight aerodynamic construction

Tandem, mountain, and racing bicycles are specialized bicycles

251

Wouldn’t It Be Nice

Be able to create specialized program objects without starting from scratch

Blinking rectanglesMoving bitmapsArbitrary precision numbers

Inheritance is the object-oriented programming mechanism for specialization

Ability to define new classes of objects using existing classes as a basis

Inheritance

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

Ability to define new classes of objects using existing classes as a basis

The new class inherits the attributes and behaviors of the parent classesNew class is aspecialized versionof the parent class Bicycle

MountainBikes

RacingBikes

TandemBikes

is-a relationships

252

A natural way to reuse codeProgramming by extension rather than reinventionObject-oriented paradigm is well-suited for this style ofprogramming

Inheritance

Bicycle

MountainBikes

RacingBikes

TandemBikes

is-a relationships

A natural way to reuse codeProgramming by extension rather than reinventionObject-oriented paradigm is well-suited for this style ofprogramming

TerminologyBase class (superclass)Derived class (subclass)

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

253

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;

};

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()

254

Class WindowObject

class WindowObject {

public:

WindowObject(SimpleWindow &w,

const Position &p);

Position GetPosition() const;

SimpleWindow& GetWindow() const;

void SetPosition(const Position &p);

private:

SimpleWindow &Window;

Position Location;

};

WindowObject Constructor

WindowObject::WindowObject(SimpleWindow &w,

const Position &p) : Window(w), Location(p) {

// No body needed

}

Members are initializedin class definition order

255

WindowObject InspectorsPosition WindowObject::GetPosition() const {

return Location;}

SimpleWindow& WindowObject::GetWindow() const {return Window;

}

WindowObject Mutatorvoid WindowObject::SetPosition(const Position &p) {

Location = p;}

256

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

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()

257

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...

};

Implementing a Derived ClassShape::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;

}

258

Basic Shapes

Width

Height

SideLength

RectangleShape TriangleShape

WIdth

Height

EllipseShape

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;

};

259

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;

};

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;

};

260

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 triangle

float c = SLength / (2.0 * cos(30 * Pi / 180.0));

float a = tan(30 * Pi / 180.0) * .5 * SLength;

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());

}

261

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;}

Fun with Shapes

262

Cleaning Up

int ApiEnd()

TWindow.Close();

return 0;

}

Inheritance and Member Accessclass 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

}

263

Inheritance and Member Accessvoid NonMemberFunction() {

SomeClass C;C.MyPublicData = 1; // access allowedC.MyProtectedData = 2; // illegalC.MyPrivateData = 3; // illegal

}

Inheritance and Member Accessclass 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

}

264

Controlling Inheritance

Inheritance 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

265

Templates and Polymorphism

Generic functions and classes

JPC and JWD © 2002 McGraw-Hill, Inc.

Polymorphic Functions

What 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 beforeWhere have we seen them before?Function overloading

Define functions or operators with the same nameRational addition operator +Function Min() for the various numeric types

Primitive polymorphism

266

Polymorphic Functions

TemplatesGenerate a function or class at compile time

Where have we seen them before?

TemplatesGenerate a function or class at compile time

Where have we seen them before?Standard Template Library

Vector and other container classes

TemplatesGenerate a function or class at compile time

Where have we seen them before?Standard Template Library

Vector and other container classes

True polymorphismChoice of which function to execute is made during run time

C++ uses virtual functions

TemplatesGenerate a function or class at compile time

Function Templates

Current scenarioWe rewrite functions Min(), Max(), and InsertionSort() for many different typesThere has to be a better way

Function templateDescribes a function format that when instantiated with particulars generates a function definition

Write once, use multiple times

267

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

Min Template

Code 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;

}

268

Min Template

Code 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;

}

Min Template

Code 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

269

Function Templates Facts

Location in program filesIn current compilers

Template definitions are part of header files

Possible template instantiation failure scenariocout << min(7, 3.14); // different parameter

// types

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;

}

}

}

270

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 sortingfind(), find_if(), count(), count_if(),min(), max(), binary_search(),lower_bound(), upper_bound(), sort()

STL provides template definitions for many programming tasksUse them! Do not reinvent the wheel!

Searching and sortingfind(), find_if(), count(), count_if(),min(), max(), binary_search(),lower_bound(), upper_bound(), sort()

Comparingequal()

STL provides template definitions for many programming tasksUse them! Do not reinvent the wheel!

Searching and sortingfind(), find_if(), count(), count_if(),min(), max(), binary_search(),lower_bound(), upper_bound(), sort()

Comparingequal()

Rearranging and copyingunique(), replace(), copy(), remove(),reverse(), random_shuffle(), merge()

STL provides template definitions for many programming tasksUse them! Do not reinvent the wheel!

Searching and sortingfind(), find_if(), count(), count_if(),min(), max(), binary_search(),lower_bound(), upper_bound(), sort()

Comparingequal()

Rearranging and copyingunique(), replace(), copy(), remove(),reverse(), random_shuffle(), merge()

Iteratingfor_each()

Class Templates

RulesType template parameters

Value template parametersPlace holder for a valueDescribed 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 fileCompilers require it for now

271

A Generic Array Representation

We will develop a class ArrayTemplate version of IntList

Provides additional insight into container classes of STL

Homegrown Generic ArraysArray<int> A(5, 0); // A is five 0's

const Array<int> B(6, 1); // B is six 1's

Array<Rational> C; // C is ten 0/1's

A = 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 ]

272

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

Auxiliary Operators

template <class T>

ostream& operator<<

(ostream &sout, const Array<T> &A);

template <class T>

istream& operator>>

(istream &sin, Array<T> &A);

273

Default Constructor

template <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];

}

}

Copy Constructor

template <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];

}

}

274

Destructor

template <class T>

Array<T>::~Array() {

delete [] Values;

}

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;

}

275

Inspector for Constant Arrays

template <class T>

const T& Array<T>::operator[](int i) const {

assert((i >= 0) && (i < size()));

return Values[i];

}

Nonconstant Inspector/Mutator

template <class T>

T& Array<T>::operator[](int i) {

assert((i >= 0) && (i < size()));

return Values[i];

}

276

Generic Array Insertion Operator

template <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

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;

}

277

Scenario

Manipulate list of heterogeneous objects with common base classExample: a list of graphical shapes to be drawn// what we would like

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

A[i].Draw();

}

Manipulate list of heterogeneous objects with common base classExample: a list of graphical shapes to be drawn// what we would like

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

A[i].Draw();

}

NeedDraw() to be a virtual function

Placeholder in the Shape class with specialized definitions in the derived class

In C++ we can come close

Virtual Functions

For virtual functionsIt 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

278

Virtual Functions

For virtual functionsIt 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’sDraw() is used

Virtual Functions

For virtual functionsIt 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’sDraw() is used

279

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;

};

Virtual Functions

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

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 timeIntroduces overhead

280

Pure Virtual Function

Has 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 classConvenient for defining interfacesBase class cannot be directly instantiated

A Shape Abstract Base Class

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() = 0; // pure virtual

// function!

private:

color Color;

};