|
|
|
|
|
|
|
Null Pointers and Null References |
|
|
|
|
|
|
|
|
When pointers are not initialized, or when they are deleted, they ought to be assigned to null (0). This is not true for references. In fact, a reference cannot be null, and a program with a reference to a null object is considered an invalid program. When a program is invalid, just about anything can happen. It can appear to work, or it can erase all the files on your disk. Both are possible outcomes of an invalid program. |
|
|
|
|
|
|
|
|
Most compilers will support a null object without much complaint, crashing only if you try to use the object in some way. Taking advantage of this, however, is still not a good idea. When you move your program to another machine or compiler, mysterious bugs might develop if you have null objects. |
|
|
|
|
|
|
|
|
Passing Function Arguments by Reference |
|
|
|
|
|
|
|
|
In Hour 5, Functions, you learned that functions have two limitations: arguments are passed by value, and the return statement can return only one value. |
|
|
|
|
|
|
|
|
Passing values to a function by reference can overcome both of these limitations. In C++, passing by reference is accomplished in two ways: using pointers and using references. The syntax is different, but the net effect is the same: rather than a copy being created within the scope of the function, the actual original object is passed into the function. |
|
|
|
|
|
|
|
|
Passing an object by reference enables the function to change the object being referred to. |
|
|
|
|
|
|
|
|
Listing 11.4 creates a swap function and passes in its parameters by value. |
|
|
|
|
|
|
|
|
LISTING 11.4 DEMONSTRATING PASS BY VALUE |
|
|
|
 |
|
|
|
|
1: //Listing 11.4 Demonstrates passing by value
2:
3: #include <iostream.h>
4:
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 << \n;
12: swap(x,y);
13: cout << Main. After swap, x: << x << y: << y << \n; |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|