Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1

2 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.

3 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

4 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

5 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);

6 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

7 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; }

8 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"; }

9 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"; }

10 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

11 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

12 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.

13 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; }

14 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

15 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;}

16 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

17 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()); }

18 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

19 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

20 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

21 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

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


Download ppt "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."

Similar presentations


Ads by Google