1 C++ Reference Parameters Math 130 B Smith: 40 to 45 min. Rate:3. Important discussion on reference parameters! B Smith: 40 to 45 min. Rate:3. Important.

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
Chapter 6: Functions.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 3 More About Classes Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Reference parameters (6.2.3) We might need a function to return more than one value Find roots of a quadratic 2 return values. What are they? Get first.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Functions Sujana Jyothi C++ Workshop Day 2. Functions 3 Parameter transmission modes pass by value (default) pass by reference (&) pass by const reference.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
The This Pointer Programming in C++ Fall 2008 Dr. David A. Gaitros
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Welcome to CISC220 Data Structures in C++ sakai.udel.edu Office Hours: Tues 3PM - 4PM / Thurs 1PM - 2PM TA: David.
C++ Programming Lecture 12 Functions – Part IV
User-Defined Functions (cont’d) - Reference Parameters.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
1 C++ Classes and Data Structures Course link…..
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
A Lecture for the c++ Course
Pointers and Pointer-Based Strings
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Pointers Psst… over there.
Pointers Psst… over there.
CS150 Introduction to Computer Science 1
Pointers & Functions.
Chapter 4 Implementing Free Functions
Reference Parameters.
Pass by Reference.
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
CS150 Introduction to Computer Science 1
Pointers & Functions.
Presentation transcript:

1 C++ Reference Parameters Math 130 B Smith: 40 to 45 min. Rate:3. Important discussion on reference parameters! B Smith: 40 to 45 min. Rate:3. Important discussion on reference parameters! B Smith: Subtle but critical!: Give two reasons a function would use pass by reference? Answer: 1. To provide a called function direct access to the passed variable. 2. To optimize speed of program. With call- by-reference, the copy constructor will not be called with each function call. B Smith: Subtle but critical!: Give two reasons a function would use pass by reference? Answer: 1. To provide a called function direct access to the passed variable. 2. To optimize speed of program. With call- by-reference, the copy constructor will not be called with each function call.

2 Overview Reference Parameters Common Errors Rules of References Use of const References as Function Arguments B Smith: Modify to show learning objects B Smith: Modify to show learning objects

3 Reference Parameters In function arguments  C and C++ use call-by-value primarily  How would you define call-by-reference ? In C, call-by-reference requires that we call functions using parameters of data type...? pointer C++ introduces another means for passing function arguments via call-by-reference This new parameter type in C++ is called a reference parameter

4 Call-By-Reference in C++ void getInput(double& receiver) { cout << “enter input number: \n”: cin >> receiver; } The & can also be placed with the parameter name void getInput(double &receiver);

5 Reference Parameters A reference variable (&) is like a pointer that is automatically dereferenced Reference variables provide us an alias for a previously declared variable

6 Passing by Value and by Reference #include using namespace std; void f(int, int&); int main() { int m=22; int n=44; cout << "m= " << m << endl; cout << "n= " << n << endl; f(m,n); cout << "m= " << m << endl; cout << "n= " << n << endl; } void f(int x, int& y) { x = x+1000; y = y*1000; }

7 swap with pointers //Demonstrates passing by reference #include void swap(int *x, int *y); int main() { int x = 5, y = 10; cout << "Main. Before swap, x: " << x << " y: " << y << "\n"; swap(&x, &y); cout << "Main. After swap, x: " << x << " y: " << y << "\n"; return 0; } void swap (int *px, int *py) { int temp; cout << "Swap. Before swap, *px: " << *px << " *py: " << *py << "\n"; temp = *px; *px = *py; *py = temp; cout << "Swap. After swap, *px: " << *px << " *py: " << *py << "\n"; }

8 swap with references //Demonstrates passing by reference // using references! #include void swap(int& x, int& y); int main() { int x = 5, y = 10; cout << "Main. Before swap, x: " << x << " y: " << y << "\n"; swap(x,y); cout << "Main. After swap, x: " << x << " y: " << y << "\n"; return 0; } void swap (int& rx, int& ry) { int temp; cout << "Swap. Before swap, rx: " << rx << " ry: " << ry << "\n"; temp = rx; rx = ry; ry = temp; cout << "Swap. After swap, rx: " << rx << " ry: " << ry << "\n"; }

9 What will be the output? #include int main ( ) { float total = 20.5 ; float& sum = total ; cout <<"sum = "<< sum << endl ; sum = 18.6 ; cout << "total = “ << total << endl ; return 0 ; } declare and initialize total declare another name for total this changes the value in total

10 Common Errors with References The references should be of the same data type as the variable to which it refers. What is the output of the following program segment? (If it even compiles!) #include using namespace std; int main() { int num = 10; float& numref = num; numref = 23.6; cout <<"The value of num is " << num << endl; <<"The value of numref is "<< numref << endl; return 0; } this does not equate numref to num

11 Reassignment of References int main() { int intOne; int &aRef = intOne; intOne = 5; int intTwo = 8; aRef = intTwo; return 0; } aRef: 8 intTwo: 5 intOne: 58 The reinitialization of the reference variable failed! B Smith: just discussed in previous slide. This slide is only useful to the extent that it shows that you’re unable to dereference. B Smith: just discussed in previous slide. This slide is only useful to the extent that it shows that you’re unable to dereference.

12 Common Errors with References int main() { int intOne; int &aRef = intOne; intOne = 5; cout << "intOne:\t" << intOne << endl; cout << "aRef:\t" << aRef << endl; cout << "&intOne:\t" << &intOne << endl; cout << "&aRef:\t\n" << &aRef << endl; int intTwo = 8; aRef = intTwo; // not what you think! cout << "intOne:\t" << intOne << endl; cout << "intTwo:\t" << intTwo << endl; cout << "aRef:\t" << aRef << endl; cout << "&intOne:\t" << &intOne << endl; cout << "&intTwo:\t" << &intTwo << endl; cout << "&aRef:\t" << &aRef << endl; return 0; }

13 Keyword const To help avoid this type of confusion, C++ allows you to explictly prevent changing the value of the referenced object Using const designates aRef as read-only int main() { int intOne; const int &aRef = intOne; intOne = 5; int intTwo = 8; aRef = intTwo; //the compiler will catch return 0; } try

14 const: Multiple Uses Data objects qualified by const cannot be modified after they have been initialized Functions qualified with const can not modify the member variable’s data: int main() { int intOne; const int &aRef = intOne; intOne = 5; int intTwo = 8; aRef = intTwo; //compiler catches return 0; } class Cat { public: Cat(int initialAge); int GetAge() const; private: int itsAge; };... void Cat::GetAge() const { return itsAge; } void Cat::GetAge() const {return itsAge;}

15 const – It’s Good Software Engineering Use const wherever possible in your programs  It reduces the likelihood of unintentional modification  It communicates to other programmers your intentions to restrict modification to data members

16 constant call-by-reference parameter int isLarger(BankAccount account1, BankAccount account2) //Returns true if the balance in acct1 is gtr than that //in acct2. Otherwise returns false. { return(account1.getBalance() > account2.getBalance()); } int isLarger(const BankAccount& account1, const BankAccount& account2) //Returns true if the balance in acct1 is gtr than that //in acct2. Otherwise returns false. { return(account1.getBalance() > account2.getBalance()); }

17 Rules of Reference Use them to create an alias to an object When a reference is created, it must be initialized  pointers can be initialized anytime Do not try to reassign a reference  but pointers can point to another object at anytime Use const to help prevent bugs in your code Don’t confuse the “address of” operator with the reference operator

18 Passing References The utility of reference parameters is in allowing you to pass-by-reference  With pass-by-reference, function calls are more efficient  No need to pass the entire object; efficient to pass a reference to the object  Can control access to the object using const B Smith: reword B Smith: reword

19 References as Function Arguments #include // will this work? void inc_counter ( int counter ) { ++counter ; } int main ( ) { int a_count = 0 ; // Random counter inc_counter ( a_count ) ; cout << a_count <<’\n’; return 0 ; } B Smith: not used Fa05 B Smith: not used Fa05

20 Correction #include void inc_counter ( int& counter ) { ++counter ; } int main ( ) { int a_count = 0 ; // Random counter inc_counter ( a_count ) ; cout << a_count << endl; return 0 ; } B Smith: Why is it that we get away with a_count ? Should we pass &a_count?? B Smith: Why is it that we get away with a_count ? Should we pass &a_count?? B Smith: not used B Smith: not used

21 Summary Reference Parameters Common Errors Rules of References References as Function Arguments