method parameters and overloading

62
Method Parameters and Overloading

Upload: tracy

Post on 24-Feb-2016

48 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Method Parameters and Overloading

MethodParameters and

Overloading

Page 2: Method Parameters and Overloading

Topics

The run-time stackPass-by-valuePass-by-referenceMethod overloading

Stub and driver methods

Page 3: Method Parameters and Overloading

ObjectivesAt the completion of this topic, students should be able to:

Correctly write methods that use pass by valueCorrectly write methods that use pass by referenceExplain what a side effect isExplain what method overloading is, and correctly usemethod overloading in a programExplain how type conversion affects method overloadingExplain what a Driver and a Stub method are, and use them in programs

Page 4: Method Parameters and Overloading

The Execution or Run-Time Stack

An important component in understanding how methodswork is the execution or run-time stack.

The following slides discuss how C# uses the run-timestack when invoking a method. Note that this is only a conceptual view of how the stack operates. It is slightlymore complicated than what is shown here, and operationof the stack depends a great deal on the operating system,the compiler, and the hardware environment.

Page 5: Method Parameters and Overloading

To get an idea of how the stack works, think of theplate dispensers that you have seen in a cafeteria

When a plate is pushedonto 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.

Page 6: Method Parameters and Overloading

When a method is called (invoked), the computerbuilds 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

Page 7: Method Parameters and Overloading

return address

parameters

local variablesStack frame

for Main( )

The Stack

Main( )’s parameterscome from the command line

control returns tothe operating system

Any variables declaredinside main’s { }

Page 8: Method Parameters and Overloading

Main( ) callsmethod ”B”

Stack framefor Main( )

Stack framefor method “B”

The Stack

return address

parameters

local variables

return address

parameters

local variables

any parameterspassed to B

returns to the pointwhere B was calledfrom inside of Main

any variablesdeclared insideof B’s { }

Page 9: Method Parameters and Overloading

When method “B” is done,its stack frame is removed from the stack.

Stack framefor Main( )

The Stack

return address

parameters

local variables

Page 10: Method Parameters and Overloading

Main( ) now goeson about its work.

Stack framefor Main( )

The Stack

return address

parameters

local variables

Page 11: Method Parameters and Overloading

Example

Page 12: Method Parameters and Overloading

using System;using static System.Console;

class Program{ static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true ); }//End Main()

static int Add(int num1, int num2) { int sum = num1 + num2; return sum; }}//End class Program

Page 13: Method Parameters and Overloading

The Stack

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true ); }

return address

no parameters

a = 5b = 3

Page 14: Method Parameters and Overloading

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true); }

The Stack

return address

no parameters

a = 5b = 3

Page 15: Method Parameters and Overloading

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true); }

The Stack

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return addressparameters

local variables

Build a Stack Frame forthe call of Method B andpush it onto the stack

Page 16: Method Parameters and Overloading

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}“);

ReadKey(true); }

The return address that goes on the stack isright here … before the assignment part of this statement.

The Stack

return address

no parameters

a = 5b = 3

The Stack

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return addressparameters

local variables B’s StackFram

e

Page 17: Method Parameters and Overloading

The Stack

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true); }

Put the parameters in the stack frame. Theseare copies of the values stored in a and b.

return address3

5

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return address3

5

local variables B’s StackFram

e

Page 18: Method Parameters and Overloading

static int Add(int num1, int num2){ int sum; sum = num1 + num2; return sum,}

num1num2

The Stack

return address3

5

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return address3

5

sum B’s StackFram

e

In the Add method, we use thesenames to refer to the parametersthat were passed to the method.

Sum is a local variabledeclared inside of the Add method

Page 19: Method Parameters and Overloading

static int Add(int num1, int num2){ int sum; sum = num1 + num2; return sum,}

The Stack

return address3

5

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return address3

5

sum B’s StackFram

eSum is a local variabledeclared inside of the Add method

8

num1num2

Page 20: Method Parameters and Overloading

static int Add(int num1, int num2){ int sum; sum = num1 + num2; return sum,}

The Stack

return address3

5

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return address3

5

sum B’s StackFram

eSum is a local variabledeclared inside of the Add method

8

eax

Copy the value of suminto the eax register 8

Values returned from a methodare passed in a special hardwareregister

num1num2

Page 21: Method Parameters and Overloading

static int Add(int num1, int num2){ int sum; sum = num1 + num2; return sum,}

The Stack

return address3

5

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

return address3

5

sum B’s StackFram

e

eax

Get the return address8

Values returned from a methodare passed in a special hardwareregister

8

8

num1num2

Page 22: Method Parameters and Overloading

int Add(int num1, int num2){ int sum; sum = num1 + num2; return sum,}

8

Values returned from a methodare passed in a special hardwareregister eax

The Stack

return address

no parameters

a = 5b = 3no parameters

return address

no parameters

a = 5b = 3

Main’s Stack

Frame

Remove B’s stack frame from the stackand go to where the return address points

Page 23: Method Parameters and Overloading

The Stack

static void Main() { int a = 5; int b = 3;

int c = Add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true); }

control returns here

return address

no parameters

a = 5b = 3c = ?

8 eax

Page 24: Method Parameters and Overloading

The Stack

static void Main() { int a = 5; int b = 3;

int c = add(a,b); WriteLine($"The answer is {c:D}");

ReadKey(true); }

8 return address

no parameters

a = 5b = 3c = 8

Page 25: Method Parameters and Overloading

Pass By ValueWhen a parameter is passed by value, a copyof the value is made and passed to the methodon the run-time stack.

Page 26: Method Parameters and Overloading

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.

Page 27: Method Parameters and Overloading

static void Main() { int num = 0, den = 0; do { Write("Enter in an integer value: "); num = int.Parse(ReadLine()); Write("Enter in another integer value: "); den = int.Parse(ReadLine()); if (den != 0) { double result = Divide(num, den); WriteLine($"{num:D}/{den:D} = {result:F2}"); } } while (den != 0);

ReadKey(true); }//End Main()

num and den are called theactual parameters, or arguments.

Page 28: Method Parameters and Overloading

let the value of num = 9and the value of den = 7

double result = Divide (num, den); if (den != 0){

WriteLine("{num:D}/{den:D} = {result:F2}");}

The Stack

return address

no parameters

num = 9den = 7

return here

Page 29: Method Parameters and Overloading

static double Divide(int n, int d) { double r = (double)n / d; n++; d++; return r; }

Notice that the originalvalues in main’s stackframe don’t change.

This is because n and dare names that are localto the Divide method.

The Stack

return address

no parameters

num = 9den = 7

return address79

r = 1.285

nd 8

10

Page 30: Method Parameters and Overloading

Control now returns to the point where thefunction was called. In this case, the returnvalue, in eax register, is then copied to “result”.

double result = Divide (num, den);

The Stack

return address

no parameters

num = 9den = 7result = 1.285

1.285 eax

Page 31: Method Parameters and Overloading

Pass By Reference

When a parameter is passed by reference, a referenceto the value is made and passed to the methodon the run-time stack.

Page 32: Method Parameters and Overloading

static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; }

the keyword ref denotes that thisparameter is passed by reference!

Page 33: Method Parameters and Overloading

double result = Divide (ref num, ref den); WriteLine($"{num:D}/{den:D} = {result:F2}");

The Stack

return address

no parameters

num = 9den = 7result = ?

Page 34: Method Parameters and Overloading

double result = Divide (ref num, ref den);

The Stack

return address

no parameters

num = 9den = 7result = ?

Return here whendone executing the function return address

ref to denref to num

Build the stack frame to call the divide method

WriteLine($"{num:D}/{den:D} = {result:F2}");

Page 35: Method Parameters and Overloading

The Stack

return address

no parameters

num = 9den = 7

return address

ref to denref to num

result = ?

static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; }

nd

Page 36: Method Parameters and Overloading

The Stack

return address

no parameters

num = 10den = 8

return address

ref to denref to num

result = ?

static double Divide(ref int n, ref int d) { double r = (double)n / d; n++; d++; return r; }

nd

These local variables, in main’sStack frame, change, becaused and n refer to them.

Page 37: Method Parameters and Overloading

If you are passing simple data to a method,you should use pass-by-value

avoids side effects!

Rule of Thumb

Page 38: Method Parameters and Overloading

If you need to change data in the callingmethod, for example swapping two values,then pass-by-reference.

When Should YouPass by Reference?

Objects are automatically passed by referencebecause it is more efficient.

If a method has to return more than one value.

Page 39: Method Parameters and Overloading

Example of Using a Side Effect

Problem: Write a method that exchanges the values of two variables.

Page 40: Method Parameters and Overloading

The exchange code ………for exchanging integers

value1 = value2;value2 = value1;

int temp = value1;value1 = value2;value2 = temp;

Page 41: Method Parameters and Overloading

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 = 5num2 = 7

return address

57

temp = 7

n2n1

These arecopies ofnum1 and num2

75

Page 42: Method Parameters and Overloading

Only the local variables allocated in Swap’sstack frame get swapped.

The original values are not changed.

To make the Swap work correctly, pass the parametersby reference.

Page 43: Method Parameters and Overloading

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 = 5num2 = 7

return address

ref to num2ref to num1

temp = 7

n2n1

These arereferences tonum1 and num2

Page 44: Method Parameters and Overloading

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 = 7num2 = 5

return address

ref to num2ref to num1

temp = 7

n2n1

So … the changesoccur to num1 andnum2

Page 45: Method Parameters and Overloading

Mixed Parameter Lists

It is perfectly valid to mix pass-by-value andpass-by-reference parameters in the same method:

void MethodTwo (ref int num1, int num2);

Page 46: Method Parameters and Overloading

Method OverloadingIn C# you can give two different methods theidentical method name (but with different parameters)

This is called method overloading.

When a method is invoked, the compiler figuresout which of the methods to use, based on the method name and the number, type and order of parameters.

Page 47: Method Parameters and Overloading

Examplestatic 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 methodthis code will invoke this method

Page 48: Method Parameters and Overloading

Method Signature

A method’s signature refers to the method nameand the number, sequence and type of parameters.

A method is overloaded when the methods have theSame name but have different signatures.

Page 49: Method Parameters and Overloading

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 doublewhen they are passed to the method.

Page 50: Method Parameters and Overloading

So … what happens if you also have thismethod 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);

?

Page 51: Method Parameters and Overloading

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.

Page 52: Method Parameters and Overloading

DriversWhen programming a large project, it is commonto code each method independently and then write a driver method that tests that method. A driver is simply aMethod that invokes through its code the method being testedin different ways to insure that the method works as expected.

Driver methods are temporary code that are not part of thefinished program, so they don’t have to be fancy.

Page 53: Method Parameters and Overloading

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 * wstatic int CalcArea (int l, int w){ return l * w;}

Page 54: Method Parameters and Overloading

int main( ){ int height=0, width=0, area=0; char yes_no = ‘N’;do {

WriteLine(“--------------------------"; Write(“Enter an integer height: “); height = int.Parse(ReadLine( ) ); Write(“Enter an integer width: “); width = int.Parse(ReadLine( ) );

area = CalcArea (height, width); WriteLine($“The area = {area:D}“);

Write(“Test another pair of values (y or n): “); yes_no = char.Parse(ReadLine( ) ); yes_no = char.ToLower(yes_no); } while (yes_no == 'y');}//End Main()

the Driver method

Page 55: Method Parameters and Overloading

Once a method has been debugged and you aresatisfied that it contains no errors, then move onto creating and testing the next method.

Each method should be tested in a program whereit is the only untested component in the program.Thus, if the program fails, you know where to lookfor the error.

Page 56: Method Parameters and Overloading

Stub MethodsSometimes it is impossible to test one methodwithout using some other method which may notyet be written or debugged.

In these cases you can write a simplified version of the required method that only delivers sufficientdata to test the other method. These simplified methods are called stubs.

Another purpose of a stud method is to be skeletonas a place holder to remind us that we need to writesuch a method.

Page 57: Method Parameters and Overloading

ExampleIf we were testing some method that depended onthe CalcArea method, and the CalcArea method hadnot 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 areacorrectly, but just getting some datareturned might be sufficient to test theother method.

Page 58: Method Parameters and Overloading

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

Page 59: Method Parameters and Overloading

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

Page 60: Method Parameters and Overloading

PracticeWrite a Main( ) method that gets two values from the userand then calls the Add method. Pass the parameters by value.

Then get two more values from the user. Call the add methodbut this time pass the parameters by reference.

Page 61: Method Parameters and Overloading

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

Page 62: Method Parameters and Overloading

We want to write a program that tells what coins to give forany amount of change from 1 to 99 cents. For example, for86 cents, the program should output something like

86 cents can be given as3 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