Method Parameters and Overloading. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
Spring Semester 2013 Lecture 5
Pointers and Arrays Chapter 12
How do Methods Work?. Let’s write a method that adds two integer values together and returns the result.
Call By Address Parameters (Pointers) Chapter 5. Functions that “return” more than a single value What if we need more than one value to be returned from.
Programming and Data Structure
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Procedures and Control Flow CS351 – Programming Paradigms.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Learning Objectives  Parameters  Call-by-value  Call-by-reference  Mixed parameter-lists  Overloading and Default Arguments  Examples, Rules  Testing.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
CompSci Data Types & Operations. CompSci The Plan  Overview  Data Types  Operations  Code Samples  ChangeMaker.java  PolarCoordinate.java.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
 2008 Pearson Education, Inc. All rights reserved Function Call Stack and Activation Records Data structure: collection of related data items.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
Data Types & Operations 1 Last Edited 1/10/04CPS4: Java for Video Games Data Types.
NA2204.1jcmt CSE 1320 Intermediate Programming C Program Basics Structure of a program and a function type name (parameters) { /* declarations */ statement;
Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;
Slide 1 Chapter 4 Parameters and Overloading. Slide 2 Learning Objectives  Parameters  Call-by-value  Call-by-reference  Mixed parameter-lists  Overloading.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Elementary C++. Procedural Programming Split your problem into simpler parts then solve each part separately Recognize common parts and solve them only.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Method Parameters and Overloading Version 1.0. Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods.
User-Defined Functions II TK1914: C++ Programming.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
A First Book of ANSI C Fourth Edition
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Function Parameters and Overloading Version 1.0. Topics Call-by-value Call-by-reference Call-by-address Constant parameters Function overloading Default.
CIS199 Test Review 2 REACH.
More About Objects and Methods
User-Written Functions
Chapter 7: User-Defined Functions II
Expressions.
Chapter 2 Assignment and Interactive Input
Method Parameters and Overloading
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Methods.
Functions Inputs Output
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Chapter 6 Intermediate-Code Generation
Parameters and Overloading
Chapter 6 Methods.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Introduction to Methods and Interfaces
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Method Parameters and Overloading

Topics The run-time stack Pass-by-value Pass-by-reference Method overloading Stub and driver methods

Objectives At the completion of this topic, students should be able to: Correctly write methods that use pass by value Correctly write methods that use pass by reference Explain what a side effect is Explain what method overloading is, and correctly use method overloading in a program Explain how type conversion affects method overloading Explain what a Driver and a Stub method are, and use them in programs

The Execution or Run-Time Stack An important component in understanding how methods work is the execution or run-time stack. The following slides discuss how C# uses the run-time stack when invoking a method. Note that this is only a conceptual view of how the stack operates. It is slightly more complicated than what is shown here, and operation of the stack depends a great deal on the operating system, the compiler, and the hardware environment.

To get an idea of how the stack works, think of the plate dispensers that you have seen in a cafeteria When a plate is pushed onto the stack, all of the other plates get pushed down. When a plate is removed from the top of the stack, all of the other plates pop up.

When a method is called (invoked), the computer builds a stack frame. The stack frame contains * the parameters that are being passed to the method * the address to return to when the method is done * any local variables declared in the method

return address parameters local variables Stack frame for Main( ) The Stack Main( )’s parameters come from the command line control returns to the operating system Any variables declared inside main’s { }

Main( ) calls method ”B” Stack frame for Main( ) Stack frame for method “B” The Stack return address parameters local variables return address parameters local variables any parameters passed to B returns to the point where B was called from inside of Main any variables declared inside of B’s { }

When method “B” is done, its stack frame is removed from the stack. Stack frame for Main( ) The Stack return address parameters local variables

Main( ) now goes on about its work. Stack frame for Main( ) The Stack return address parameters local variables

Example

using System; class Program { static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); }//End Main() static int Add(int num1, int num2) { int sum = num1 + num2; return sum; } }//End class Program

The Stack static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } return address no parameters a = 5 b = 3

static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } The Stack return address no parameters a = 5 b = 3

static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } The Stack return address no parameters a = 5 b = 3 Main’s Stack Frame return address parameters local variables Build a Stack Frame for the call of Method B and push it onto the stack

static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } The return address that goes on the stack is right here … before the assignment part of this statement. The Stack return address no parameters a = 5 b = 3 The Stack return address no parameters a = 5 b = 3 Main’s Stack Frame return address parameters local variables B’s Stack Frame

The Stack static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } Put the parameters in the stack frame. These are copies of the values stored in a and b. return address 3535 no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 Main’s Stack Frame return address 3535 local variables B’s Stack Frame

static int Add(int num1, int num2) { int sum; sum = num1 + num2; return sum, } num1 num2 The Stack return address 3535 no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 Main’s Stack Frame return address 3535 sum B’s Stack Frame In the Add method, we use these names to refer to the parameters that were passed to the method. Sum is a local variable declared inside of the Add method

static int Add(int num1, int num2) { int sum; sum = num1 + num2; return sum, } The Stack return address 3535 no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 Main’s Stack Frame return address 3535 sum B’s Stack Frame Sum is a local variable declared inside of the Add method 8 num1 num2

static int Add(int num1, int num2) { int sum; sum = num1 + num2; return sum, } The Stack return address 3535 no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 Main’s Stack Frame return address 3535 sum B’s Stack Frame Sum is a local variable declared inside of the Add method 8 eax Copy the value of sum into the eax register 8 Values returned from a method are passed in a special hardware register num1 num2

static int Add(int num1, int num2) { int sum; sum = num1 + num2; return sum, } The Stack return address 3535 no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 return address no parameters a = 5 b = 3 Main’s Stack Frame return address 3535 sum B’s Stack Frame eax Get the return address 8 Values returned from a method are passed in a special hardware register 8 8 num1 num2

int Add(int num1, int num2) { int sum; sum = num1 + num2; return sum, } 8 Values returned from a method are passed in a special hardware register eax The Stack return address no parameters a = 5 b = 3 no parameters return address no parameters a = 5 b = 3 Main’s Stack Frame Remove B’s stack frame from the stack and go to where the return address points

The Stack static void Main() { int a = 5; int b = 3; int c = Add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } control returns here return address no parameters a = 5 b = 3 c = ? 8 eax

The Stack static void Main() { int a = 5; int b = 3; int c = add(a,b); Console.WriteLine("The answer is {0}", c); Console.ReadLine( ); } 8 return address no parameters a = 5 b = 3 c = 8

Pass By Value When a parameter is passed by value, a copy of the value is made and passed to the method on the run-time stack.

static double Divide(int n, int d) { double r = (double)n / d; n++; d++; return r; } These names are local to the method Divide( ). The parameters passed to the method are given these names so that we can use them inside of the method.

static void Main() { int num = 0, den = 0; do { Console.Write("Enter in an integer value: "); num = int.Parse(Console.ReadLine()); Console.Write("Enter in another integer value: "); den = int.Parse(Console.ReadLine()); if (den != 0) { double result = Divide(num, den); Console.WriteLine("{0}/{1} = {2}", num, den, result); } } while (den != 0); Console.ReadLine( ); }//End Main() num and den are called the actual parameters, or arguments.

let the value of num = 9 and the value of den = 7 double result = Divide (num, den); if (den != 0) { Console.WriteLine("{0}/{1} = {2}", num, den, result); } The Stack return address no parameters num = 9 den = 7 return here

static double Divide(int n, int d) { double r = (double)n / d; n++; d++; return r; } Notice that the original values in main’s stack frame don’t change. This is because n and d are names that are local to the Divide method. The Stack return address no parameters num = 9 den = 7 return address 7979 r = n d 8 10

Control now returns to the point where the function was called. In this case, the return value, in eax register, is then copied to “result”. double result = Divide (num, den); The Stack return address no parameters num = 9 den = 7 result = eax

Pass By Reference When a parameter is passed by reference, a reference to the value is made and passed to the method on the run-time stack.

static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; } the keyword ref denotes that this parameter is passed by reference!

double result = Divide (ref num, ref den); Console.WriteLine("{0}/{1} = {2}", num, den, result); The Stack return address no parameters num = 9 den = 7 result = ?

double result = Divide (ref num, ref den); Console.WriteLine("{0}/{1} = {2}", num, den, result); The Stack return address no parameters num = 9 den = 7 result = ? Return here when done executing the function return address ref to den ref to num Build the stack frame to call the divide method

The Stack return address no parameters num = 9 den = 7 return address ref to den ref to num result = ? static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; } n d

The Stack return address no parameters num = 10 den = 8 return address ref to den ref to num result = ? static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; } n d These local variables, in main’s Stack frame, change, because d and n refer to them.

If you are passing simple data to a method, you should use pass-by-value avoids side effects! Rule of Thumb

If you need to change data in the calling method, for example swapping two values, then pass-by-reference. When Should You Pass by Reference? Objects are automatically passed by reference because it is more efficient. If a method has to return more than one value.

Example of Using a Side Effect Problem: Write a method that exchanges the values of two variables.

The exchange code ……… for exchanging integers value1 = value2; value2 = value1; int temp = value1; value1 = value2; value2 = temp;

Using pass by value … void Swap (int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; } int num1 = 5; int num2 = 7; Swap (num1, num2); The Stack return address no parameters num1 = 5 num2 = 7 return address 5757 temp = 7 n2 n1 These are copies of num1 and num2 7575

Only the local variables allocated in Swap’s stack frame get swapped. The original values are not changed. To make the Swap work correctly, pass the parameters by reference.

Using pass by reference … void Swap (ref int n1, ref int n2) { int temp = n1; n1 = n2; n2 = temp; } int num1 = 5; int num2 = 7; Swap (ref num1, ref num2); The Stack return address no parameters num1 = 5 num2 = 7 return address ref to num2 ref to num1 temp = 7 n2 n1 These are references to num1 and num2

Using pass by reference … void Swap (ref int n1, ref int n2) { int temp = n1; n1 = n2; n2 = temp; } int num1 = 5; int num2 = 7; Swap (ref num1, ref num2); The Stack return address no parameters num1 = 7 num2 = 5 return address ref to num2 ref to num1 temp = 7 n2 n1 So … the changes occur to num1 and num2

Mixed Parameter Lists It is perfectly valid to mix pass-by-value and pass-by-reference parameters in the same method: void MethodTwo (ref int num1, int num2);

Method Overloading In C# you can give two different methods the identical method name (but with different parameters) This is called method overloading. When a method is invoked, the compiler figures out which of the methods to use, based on the method name and the number, type and order of parameters.

Example static int Max (int n1, int n2) { if ( n1 < n2 ) return n2; else return n1; } static int Max (int n1, int n2, int n3) { if ( n1 < n2 ) if ( n2 < n3 ) return n3; else return n2; else if ( n1 < n3 ) return n3; else return n1; } this method has two parameters this method has three parameters int biggest = Max (5, 3); int largest = Max (5,3,7); this code will invoke this method

Method Signature A method’s signature refers to the method name and the number, sequence and type of parameters. A method is overloaded when the methods have the Same name but have different signatures.

Type Conversion and Overloading static double Mpg (double miles, double gallons) { return (miles / gallons); } if this method is called with the following code … int m = 15; int g = 3; double result = Mpg (m, g); m and g will be converted to double when they are passed to the method.

So … what happens if you also have this method in your program? int Mpg (int goals, int misses) { return ( goals – misses); } and you make the method call int miles = 2; int gallons = 8; int result = Mpg (m,g); ?

Rules for Resolving Overloading 1.If there is a method whose signature exactly matches the parameters in the method call, than that method is selected first. 2.Otherwise, if there is a method whose signature matches the parameters of the method call, after doing some type upcasting conversion, then that method is selected.

Drivers When programming a large project, it is common to code each method independently and then write a driver method that tests that method. A driver is simply a Method that invokes through its code the method being tested in different ways to insure that the method works as expected. Driver methods are temporary code that are not part of the finished program, so they don’t have to be fancy.

Example // calcArea method // purpose: calculate the area of a rectangular region // parameters: a integer length l and an integer width w // returns: an integer result = l * w static int CalcArea (int l, int w) { return l * w; }

int main( ) { int height=0, width=0, area=0; char yes_no = ‘N’; do { Console.WriteLine(“ "; Console.Write(“Enter an integer height: “); height = int.Parse(Console.ReadLine( ) ); Console.Write(“Enter an integer width: “); width = int.Parse(Console.ReadLine( ) ); area = CalcArea (height, width); Console.WriteLine(“The area = {0}“, area); Console.Write(“Test another pair of values (y or n): “); yes_no = char.Parse(Console.ReadLine( ) ); yes_no = char.ToLower(yes_no); } while (yes_no == 'y'); }//End Main() the Driver method

Once a method has been debugged and you are satisfied that it contains no errors, then move on to creating and testing the next method. Each method should be tested in a program where it is the only untested component in the program. Thus, if the program fails, you know where to look for the error.

Stub Methods Sometimes it is impossible to test one method without using some other method which may not yet be written or debugged. In these cases you can write a simplified version of the required method that only delivers sufficient data to test the other method. These simplified methods are called stubs. Another purpose of a stud method is to be skeleton as a place holder to remind us that we need to write such a method.

Example If we were testing some method that depended on the CalcArea method, and the CalcArea method had not yet been written and tested, we could provide a stub that might look like this -- int CalcArea ( int w, int l) { return 100; } the method does not calculate the area correctly, but just getting some data returned might be sufficient to test the other method.

Practice Write a method, Add( ), that takes two integer parameters. The parameters are passed by value. The method returns the sum as an integer.

Practice Write a method, Add( ), that takes two integer parameters. The parameters are passed by reference. The method returns the sum as an integer.

Practice Write a Main( ) method that gets two values from the user and then calls the Add method. Pass the parameters by value. Then get two more values from the user. Call the add method but this time pass the parameters by reference.

Practice Write a program that converts time in 24 hour notation to its equivalent time in 12 hour notation. For example, 1320 would convert to 1:20pm. Write a method that does the conversion. How will you pass the parameters? Could you have used this method in the first project that you did?

We want to write a program that tells what coins to give for any amount of change from 1 to 99 cents. For example, for 86 cents, the program should output something like 86 cents can be given as 3 quarter(s) 1 dime(s) and 1 penny(pennies) Only use coin denominations of 25 cents ( quarters ), 10 cents ( dimes ), and 1 cent ( pennies ). Your program should use a method of the following form: void ComputeCoins ( int coinValue, ref int number, ref int left ); For example, if the amount left is 86 cents, and the coinValue is 25, the value of number will be 3 and the new amount left will be 11. Practice