The actual values needed, the square and cube of number, are not returned by using the
return mechanism; rather, they are returned by changing the pointers that were passed
into the function.
On lines 36 and 37, the pointers are assigned their return values. These values are
assigned to the original variables by the use of indirection. You know this by the use of
the dereference operator (*) with the pointer names. On line 38,Valueis assigned a suc-
cess value and then on line 40 it is returned.
270 Day 9
Because passing by reference or by pointer allows uncontrolled access to
object attributes and methods, you should pass the minimum required for
the function to do its job. This helps to ensure that the function is safer to
use and more easily understandable.
TIP
Returning Values by Reference ......................................................................
Although Listing 9.8 works, it can be made easier to read and maintain by using
references rather than pointers. Listing 9.9 shows the same program rewritten to use
references.
Listing 9.9 also includes a second improvement. An enumhas been added to make the
return value easier to understand. Rather than returning 0 or 1, using an enum, the pro-
gram can return SUCCESSor FAILURE.
LISTING9.9 Rewritten Using References
1: //Listing 9.9
2: // Returning multiple values from a function
3: // using references
4: #include <iostream>
5:
6: using namespace std;
7:
8: enum ERR_CODE { SUCCESS, ERROR };
9:
10: ERR_CODE Factor(int, int&, int&);
11:
12: int main()
13: {
14: int number, squared, cubed;
15: ERR_CODE result;
16:
17: cout << “Enter a number (0 - 20): “;