470 likes | 482 Views
Explore reference parameters, inlining, function overloading, templates, recursion, and more in C++. Learn how to use value and reference parameters effectively. Study numerical computing and class scope rules.
E N D
Functions in Depth Chapter 8
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 C++ An Introduction to Computing, 3rd ed.
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 • Objects C++ An Introduction to Computing, 3rd ed.
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. C++ An Introduction to Computing, 3rd ed.
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 parameterchanges the value of its corresponding argument. C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
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 functionfor (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 C++ An Introduction to Computing, 3rd ed.
Parameters • Value parameter • A distinct variable containing a copy of its argument • In previous example, op1 and op2 are value parameters C++ An Introduction to Computing, 3rd ed.
Parameters • Reference 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 C++ An Introduction to Computing, 3rd ed.
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; C++ An Introduction to Computing, 3rd ed.
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. C++ An Introduction to Computing, 3rd ed.
Solution • Constant reference parameters • Reference parameters whose declaration is preceded by the keyword const. string mascot (const string& university){ if (university == "Illinois") return "Fighting Illini"; . . . } • const reference parameters are read-only aliases of their arguments • But they cannot be changed. C++ An Introduction to Computing, 3rd ed.
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. • Objects Osgood Dude Smart C++ An Introduction to Computing, 3rd ed.
Algorithm, Coding • Use find() to find the index of first blank in fullName • Use substr() to extract firstName • Use find() to find index of second blank in fullName • Use substr() to extract middleName • Use size() and result of 3 to find number of characters in lastName • Use substr() to extract lastName • View source code, sample run, Figure 8.3 C++ An Introduction to Computing, 3rd ed.
value parameters reference parameters 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){ . . . } C++ An Introduction to Computing, 3rd ed.
Algorithm • Compute change as purchaseAmount minus payment • If change positive then • Compute dollars in change, remove dollars from change • Compute quarters in change, remove quarters from change • . . . OtherwiseSet each of dollars, quarters … to zero C++ An Introduction to Computing, 3rd ed.
What would the function calls look like? 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 C++ An Introduction to Computing, 3rd ed.
Note how both parameters are received and sent back out … both must be reference parameters Examples of Parameter UsageProblem 3 • It is often necessary to interchange the values of two variables • We need a swap function to accomplish thisswap (value1, value2); • We will consider swapping two character values • Objects C++ An Introduction to Computing, 3rd ed.
Discuss why the temporary variable is needed. What gets printed? 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; C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
The same identifier can be used in different functions without conflict. Two functions can have the same name. 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;} C++ An Introduction to Computing, 3rd ed.
This double use of the identifier is illegal because they are both declared within the same block. 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 C++ An Introduction to Computing, 3rd ed.
Scope Rules • If an identifier is declared within a block, its scope runs from that point to end of block • If an identifier is a function parameter, its scope is the body of the function • If an identifier is declared in the initialization of a for loop, its scope is to the end of the loop • 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 C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
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; C++ An Introduction to Computing, 3rd ed.
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) C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
Function Templates • Templates provide a pattern for the compiler to generate functions for whatever type of parameters are used in the calltemplate <typename Item>inline void swap( Item& first, Item& second){ Item temp = first; first = second; second = temp;} 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 C++ An Introduction to Computing, 3rd ed.
Recursion • Consider a function to calculate n-factorial • From mathematics • It can be defined recursively as follows C++ An Introduction to Computing, 3rd ed.
Recursion • A recursive definition must have two parts • An anchor or baseThe value is specified for one or more values of the parameter(s) • An inductive or recursive stepThe value for the parameter is specified in terms of previously defined value(s) and/or parameters C++ An Introduction to Computing, 3rd ed.
Recursion • To calculate 5! we go through the following steps: • Then we backtrack C++ An Introduction to Computing, 3rd ed.
The anchor The inductive step 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);} C++ An Introduction to Computing, 3rd ed.
Execution of Recursive Function • Observe the sequence of recursive calls when int number = factorial(4); Successiverecursivecalls C++ An Introduction to Computing, 3rd ed.
Execution of Recursive Function • When factorial(n - 1) eventually sends a 0 as the value parameter, the anchor statement executes • No more recursive calls . . . C++ An Introduction to Computing, 3rd ed.
1 2 6 24 Execution of Recursive Function • Now the calculated values are returned C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
Towers of Hanoi • Observe game tree • Shows possible configurations possible with two disks • Highlighted path is solution C++ An Introduction to Computing, 3rd ed.
Towers of Hanoi • Move strategy coded, Figure 8.10 • Driver program Figure 8.11 • Sample run C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
Numerical Methods Example • Approximating the area under a curve • Numerical methods approach • Divide region into strips, sum the areas • Trapezoidal method C++ An Introduction to Computing, 3rd ed.
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 instantiated class 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 C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
Class Variables • Declare a class variable with static • Class variable initialized with class variable initialization statementint Sphere::inumbeOfSpheres = 0; • A constructor or instance method can access, modify value of class variable • Accessors for class variables are usually class methods • Only a class method is allowed to access a class variable C++ An Introduction to Computing, 3rd ed.
The name of the destructor for a class is always the tilde ~ followed by the name of the class. 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 destructorinline Sphere::~Sphere(){ numberOfSpheres--; } View Figure 8.15 for program which tests the execution of a destructor. C++ An Introduction to Computing, 3rd ed.
Class Scope Additional scope rules for classes: • 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 • 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 C++ An Introduction to Computing, 3rd ed.