functions in depth chapter 8. c++ an introduction to computing, 3rd ed. 2 objectives expand on...

47
Functions in Depth Chapter 8

Upload: delilah-phelps

Post on 17-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

Functions in Depth

Chapter 8

Page 2: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 2

Objectives

Expand on previous intro to functions

A detailed look at reference parameters

See why and when to use inlining

Study scope rules, function overloading, and templates

Introduce recursion

A first look at numerical computing

Examine scope rules for classes

Page 3: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 3

Introductory ExampleOne-Step Integer Division

Consider the task to divide two integers• We obtain both the quotient and the remainder• We desire a function which returns both values

DescriptionSoftware Objects

Type Kind Movement Name

first operand int varying received op1

second operand int varying received opt2

quotient of division int varying returned quotient

remainder of div int varying returned remainder

Objects

Page 4: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 4

Problem …

According to the chart of objects, we must return two objects … • Functions may return only one object

Normal parameters are called value parameters and are built as copies of their arguments.

Changing a value parameter changes the copy, not its corresponding argument.

Page 5: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 5

Solution – Reference Parameters

Reference parameters • Parameters declared with an ampersand (&) • Following the parameter’s type (and before its

name).

A reference parameter is an alias its corresponding argument.• Acts like another name for actual parameter

Changing the value of a reference parameter changes the value of its corresponding argument.

Page 6: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 6

Solution – Reference Parameters

Function stub with reference parameters:

void divideInts (int op1, int op2, int& quotient, int& remainder) { … }

quotient and remainder receive the appropriate values in assignment statements

The parameters in the call receive those same values

Page 7: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 7

Using Reference Parameters

Note source function source code, Figure 8.1• Driver program, Figure 8.2 • and sample runs.

Note quot and rem in the call of the function for (int j = 1; j <= 4; j++) { for (int i = 1; i <= 4; i++) { divideInts (i,j,quot,rem); …

These hold the values sent back from the function

Page 8: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 8

Parameters

Value parameter• A distinct variable containing a copy of its

argument• In previous example, op1 and op2 are value

parameters

Page 9: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 9

ParametersReference parameter• An alias of (alternate name for) the

corresponding argument in the call• Changes to value of reference parameter will

change the value of the corresponding argument in the call

1

2

Page 10: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 10

Reference Parameters

The parameters in the call must be variables of the same type as in the declaration

Large objects passed as value parameters can take up excessive space, time

string mascot (string& university){ if (university == "Illinois") return "Fighting Illini"; …}----cout << mascot (school) << endl;

Page 11: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 11

Consider

Copying argument school consumes time.• Especially if the argument is a large structure

Creating an alias for an argument takes almost no time.We could speed up calls to our function by making parameter university a reference parameter.However, we then run a risk• We might change school if we mistakenly change university.

Page 12: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 12

Solution

Constant reference parameters • Reference parameters whose declaration is

preceded by the keyword const.

const reference parameters are read-only aliases of their arguments • But they cannot be changed.

string mascot (const string& university){ if (university == "Illinois") return "Fighting Illini"; . . . }

Page 13: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 13

Examples of Parameter UsageProblem 1

Consider problem of decomposing a person's full name with a function and passing back first, middle, and last name.

DescriptionSoftware Objects

Type Kind Movement Name

full name string varying received fullName

first name string varying sent back firstName

middle name string varying sent back middleName

last name string varying sent back lastName

Objects Osgood Dude Smart

Page 14: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 14

Algorithm, Coding1. Use find() to find the index of first blank in

fullName

2. Use substr() to extract firstName3. Use find() to find index of second blank in

fullName

4. Use substr() to extract middleName5. Use size() and result of 3 to find number of

characters in lastName6. Use substr() to extract lastName

View source code, sample run, Figure 8.3

Page 15: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 15

Examples of Parameter UsageProblem 2

Consider an automated cash register• Two inputs: amount of purchase, amount given

as payment• Five outputs: amount of change in dollars,

quarters, dimes, nickels, and pennies

Function stub:void makeChange (double purchaseAmount, double payment, int& dollars, int& quarters, int& dimes, int& nickels, int& pennies){ . . . }

value parametersvalue parameters

reference parameters

reference parameters

Page 16: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 16

Algorithm

1. Compute change as purchaseAmount minus payment

2. If change positive then

a. Compute dollars in change, remove dollars from change

b. Compute quarters in change, remove quarters from change

c. . . .

OtherwiseSet each of dollars, quarters … to zero

Page 17: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 17

Coding, Alternatives

Note source code, Figure 8.4• Note the divdeInts() function from earlier in

chapter

void divideInts (int op1, int op2, int& quotient, int& remainder) { … }

could have been used nicely after the if (change > 0) portion of the function

Driver program, Figure 8.5• Sample run What would the function

calls look like?

What would the function calls look like?

Page 18: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 18

It is often necessary to interchange the values of two variables• We need a swap function to accomplish this

swap (value1, value2);• We will consider swapping two character values

Examples of Parameter UsageProblem 3

DescriptionSoftware Objects

Type Kind Movement Name

first variable char varyingboth received in

and sent back outfirst

second variable char varyingboth received in

and sent back outsecond

Objects

Note how both parameters are received

and sent back out … both must be reference

parameters

Note how both parameters are received

and sent back out … both must be reference

parameters

Page 19: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 19

Coding

Figure 8.6

void swap(char& first, char& second){char temporary = first;first = second;second = temporary;}

Call of the function:string name = "Snidly";swap (name[0], name[3]);cout << name << endl;

Discuss why the temporary variable is

needed.

Discuss why the temporary variable is

needed.

What gets printed?What gets printed?

Page 20: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 20

Inline Functions

When one function calls another void f( int n ) { ... x = g(n); ... }

the process takes time for the program to transfer to a different location within the machine code

Possible to avoid the overhead required by this transfer

Page 21: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 21

Inline Functions

Use the inline specifier in the prototype and definitioninline double fahrToCelsius (double temp); . . .inline double fahrToCelsius (double temp){ return (temp – 32.0)/1.8; }

The compiler now places actual code for the function in each location it is called• There is no jump to one location for the code

at run time

Page 22: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 22

Inline Functions and Libraries

Normal header files• Prototypes in library header (.h) file• Definitions in an implementation (.cpp) file

For inline library functions• Definition must be in the header file

Note example, Figure 8.7

Inline functions are a trade-off• Faster execution at run time … but … • Larger .exe file

Page 23: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 23

Scope, Overloading

What might an inexperienced programmer see as mistakes in these two legal functions from the same program?

inline int sum (int n){ return n * (n + 1) / 2; }

inline int sum (int m, int n){ assert ( m < n) ; return (n – m + 1) * (n + m) / 2;}

The same identifier can be used in different functions

without conflict.

The same identifier can be used in different functions

without conflict.

Two functions can have the same

name.

Two functions can have the same

name.

Page 24: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 24

Scope, Overloading

What is different about this illegal use of the same identifier?

void f(){ int value; . . . char value; . . . }

The scope of an identifier is the portion of the program where it can be accessed

This double use of the identifier is illegal because they are both declared within the same block.

This double use of the identifier is illegal because they are both declared within the same block.

Page 25: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 25

Scope Rules

1. If an identifier is declared within a block, its scope runs from that point to end of block

2. If an identifier is a function parameter, its scope is the body of the function

3. If an identifier is declared in the initialization of a for loop, its scope is to the end of the loop

4. If an identifier's scope is declared outside all blocks and it is not a parameter, then it scope runs from that point to the end of the file

Page 26: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 26

Implications of Scope Rules

Rule 4 implies• A function prototype must come before the

function is called• Header files must be #included before

elements of that library are used

Within the scope of an identifier, no redeclaration of that identifier that results in an ambiguity for the compiler is permitted

Page 27: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 27

Namespaces

Declarations can be placed within a namespace blocknamespace Whatever{ int value; // other declarations, definitions … }

Elements within the namespace can be accessed• By using the fully qualified nameWhatever::value

• By its unqualified name, value, if usingusing namespace Whatever::value;orusing namespace Whatever;

Page 28: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 28

Function Overloading

Why can we have two functions with the same name and at the same time hold to the rule about no redeclaration of identifiers?

The function signatures were different• Different numbers of parameters• Different types of parameters

When this occurs we say the function name has been "overloaded"

inline int sum (int n);inline int sum (int m, int n)

Page 29: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 29

Function Templates

Recall our swap function for characters• Would be useful to be able to swap elements

of any type

One solution . . .• Overload the swap function many times in a

swap libraryswap (int& first, int& second);swap (double& first, double& second); . . .

C++ provides a better way … templates

Page 30: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 30

Function Templates

Templates provide a pattern for the compiler to generate functions for whatever type of parameters are used in the call

template <typename Item>inline void swap( Item& first, Item& second){ Item temp = first; first = second; second = temp;}

Think of Item as being a "type parameter"

Think of Item as being a "type parameter"

Note that both the prototype and the definition of the template

function must be in the same file which is #included

Note that both the prototype and the definition of the template

function must be in the same file which is #included

Page 31: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 31

Recursion

Consider a function to calculate n-factorial• From mathematics

• It can be defined recursively as follows

1 if n is 0

1 2 ... if n > 0n

n

1 if n is 0

n (n-1)! if n > 0n

Page 32: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 32

Recursion

A recursive definition must have two parts1. An anchor or base

The value is specified for one or more values of the parameter(s)

2. An inductive or recursive stepThe value for the parameter is specified in terms of previously defined value(s) and/or parameters

1 if n is 0

n (n-1)! if n > 0n

Page 33: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 33

Recursion

To calculate 5! we go through the following steps:

Then we backtrack

Page 34: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 34

Recursive Function

Note the source code for the factorial function, Figure 8.9int factorial (int n){ assert (n >= 0); if (n == 0) return 1; else return n * factorial (n – 1);}

The anchorThe anchor

The inductive stepThe inductive step

Page 35: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 35

Execution of Recursive FunctionObserve the sequence of recursive calls when int number = factorial(4);

Successiverecursive

calls

Page 36: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 36

Execution of Recursive Function

When factorial(n - 1) eventually sends a 0 as the value parameter, the anchor statement executes• No more recursive calls

. . .

Page 37: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 37

Execution of Recursive Function

Now the calculated values are returned

112266

2424

Page 38: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 38

Recursive Example 2:The Towers of Hanoi

A puzzle to move the stack of disks from one peg to another• When disk moved, must be placed on a peg• Only one disk at a time, must be top disk• Never put larger disk on top of smaller

Page 39: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 39

Towers of Hanoi

Observe game tree• Shows possible configurations possible with

two disks• Highlighted path is solution

Page 40: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 40

Towers of Hanoi

Move strategy coded, Figure 8.10

Driver program Figure 8.11• Sample run

Page 41: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 41

Numerical Methods

Mathematical models used to solve practical problems

Computer programs are used to manipulate such equations• Called "numerical methods"

Examples– Curve fitting — Differential

equations– Equation solving — Solving linear systems– Integration

Page 42: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 42

Numerical Methods Example

Approximating the area under a curve

Numerical methods approach• Divide region into strips, sum the areas• Trapezoidal method

( )b

a

Area f x dx

Page 43: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 43

OBJECTive Thinking:Class Variables, Instance Variables, Scope

Class variables• Some variables may be for the use of the class, itself

… not the user of the class

Example:• A variable to keep track of how many class objects of

a certain type have been instantiatedclass Sphere {

public: Sphere(); int getNumberOfSpheres(); … private: double myRadius, myDensity, myWeight; int numberOfSpheres; . . .

As it is here, this would not accomplish what we intend.

See Figure 8.12

View test program Figure 8.13

As it is here, this would not accomplish what we intend.

See Figure 8.12

View test program Figure 8.13

Page 44: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 44

Class Variables

Instance variables • Associated with an object

Class variables • Associated with the class

Note the declaration of numberOfSpheres• Declared as a class variable• Initialize it to zero exactly once• Increment it in the constructor• Declare getNumberOfSpheres as a class

method

Page 45: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 45

Class Variables

Declare a class variable with staticClass variable initialized with class variable initialization statementint Sphere::inumbeOfSpheres = 0;

A constructor or instance method can access, modify value of class variableAccessors for class variables are usually class methods• Only a class method is allowed to access a

class variable

Page 46: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 46

Destructors

An object ceases to exist (have no memory allocated for it) when• The program moves outside the scope of the

object

If we want to decrement the object count with our object variable• We use a special function called a destructor

inline Sphere::~Sphere(){ numberOfSpheres--; }

The name of the destructor for a class is always the tilde ~ followed by the

name of the class.

The name of the destructor for a class is always the tilde ~ followed by the

name of the class.

View Figure 8.15 for program which tests the execution of a destructor.

View Figure 8.15 for program which tests the execution of a destructor.

Page 47: Functions in Depth Chapter 8. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on previous intro to functions A detailed look at reference

C++ An Introduction to Computing, 3rd ed. 47

Class ScopeAdditional scope rules for classes:

5. If an identifier is declared anywhere in a class• It's scope begins at the beginning of the class and

ends at the end of the class• It extends into every method of the class

6. If an identifier is declared under public:• An instance variable may be accessed outside the

class using the name of the instance and dot notation

• Otherwise (a class variable or method) may be accessed using class name and scope operator