< previous page page_172 next page >

Page 172
If swap() had been a member function of a class, the class declaration, also available in a header file, would have supplied this information.
In C++, clients of classes and functions rely on the header file to tell all that is needed; it acts as the interface to the class or function. The actual implementation is hidden from the client. This enables the programmer to focus on the problem at hand and to use the class or function without concern for how it works.
Returning Multiple Values
As discussed, functions can only return one value. What if you need to get two values back from a function? One way to solve this problem is to pass two objects into the function, by reference. The function can then fill the objects with the correct values. Because passing by reference enables a function to change the original objects, this effectively lets the function return two pieces of information. This approach bypasses the return value of the function, which can then be reserved for reporting errors.
Once again, this can be done with references or pointers. Listing 11.7 demonstrates a function that returns three values, two as pointer parameters and one as the return value of the function.
LISTING 11.7 RETURNING VALUES WITH POINTERS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:      //Listing 11.7
 2:      // Returning multiple values from a function
 3:
 4:      #include <iostream.h>
 5:
 6:      short Factor(int, int*, int*);
 7:
 8:     int main()
 9:     {
10:        int number, squared, cubed;
11:        short error;
12:
13:        cout << Enter a number (0 - 20): ;
14:        cin >> number;
15:
16:        error = Factor(number, &squared, &cubed);
17:
18:        if (!error)
19:        {
20:            cout << number:  << number << \n;
21:            cout << square:  << squared << \n;
22:            cout << cubed:   << cubed   << \n;
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_172 next page >

If you like this book, buy it!