Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 263

9


Passing an object by reference enables the function to change the object being referred
to. On Day 5, you learned that functions are passed their parameters on the stack. When
a function is passed a value by reference (using either pointers or references), the address
of the original object is put on the stack, not the entire object. In fact, on some comput-
ers, the address is actually held in a register and nothing is put on the stack. In either
case, because an address is being passed, the compiler now knows how to get to the orig-
inal object, and changes are made there and not in a copy.
Recall that Listing 5.5 on Day 5 demonstrated that a call to the swap()function did not
affect the values in the calling function. Listing 5.5 is reproduced here as Listing 9.5, for
your convenience.

LISTING9.5 Demonstrating Passing by Value


1: //Listing 9.5 - Demonstrates passing by value
2: #include <iostream>
3:
4: using namespace std;
5: void swap(int x, int y);
6:
7: int main()
8: {
9: int x = 5, y = 10;
10:
11: cout << “Main. Before swap, x: “ << x << “ y: “ << y << endl;
12: swap(x,y);
13: cout << “Main. After swap, x: “ << x << “ y: “ << y << endl;
14: return 0;
15: }
16:
17: void swap (int x, int y)
18: {
19: int temp;
20:
21: cout << “Swap. Before swap, x: “ << x << “ y: “ << y << endl;
22:
23: temp = x;
24: x = y;
25: y = temp;
26:
27: cout << “Swap. After swap, x: “ << x << “ y: “ << y << endl;
28: }

Main. Before swap, x: 5 y: 10
Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 5 y: 10

OUTPUT

Free download pdf