240 likes | 482 Views
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.
E N D
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: 40 to 45 min. Rate:3. Important discussion on reference parameters! C++ Reference Parameters Math 130
B Smith: Modify to show learning objects Overview • Reference Parameters • Common Errors • Rules of References • Use of const • References as Function Arguments
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
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);
Reference Parameters • A reference variable (&) is like a pointer that is automatically dereferenced • Reference variables provide us an alias for a previously declared variable
Passing by Value and by Reference #include <iostream> 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; } voidf(int x, int& y) { x = x+1000; y = y*1000; }
//Demonstrates passing by reference #include <iostream> 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"; } swap with pointers
//Demonstrates passing by reference // using references! #include <iostream> 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"; } swap with references
What will be the output? #include <iostream> 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
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 <iostream> 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
B Smith: just discussed in previous slide. This slide is only useful to the extent that it shows that you’re unable to dereference. 5 intOne: 8 intTwo: Reassignment of References int main() { int intOne; int &aRef = intOne; intOne = 5; int intTwo = 8; aRef = intTwo; return 0; } The reinitialization of the reference variable failed! 5 8 aRef:
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 try int main() { int intOne; const int &aRef = intOne; intOne = 5; int intTwo = 8; aRef = intTwo; //the compiler will catch return 0; }
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;}
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
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()); }
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
Summary • Reference Parameters • Common Errors • Rules of References • References as Function Arguments