However strange it may seem, sometimes we do not want a function to return a value. Now why would we want to do something as crazy as that??
void PrintInt(int n) { cout << n << endl; }Call
PrintInt(7);
return;
This is the neat way in which you can make a change to a formal parameter while also affecting the corresponding actual parameter. We do this by using the '&' before the formal parameter in the function header. See CallByReference.ccp Demo
Now one might ask, "How am I going to keep track of such a complicated mess?" You do this by playing CHASE THE ARROW (which is sort of like chasing your tail, but much more productive!!)
|
Now think about this...
What must the actual parameter be??? Well, since the call by reference changes the actual parameter it must be a variable .
AND ANOTHER THING!!
Names have nothing to do with parameter correspondence.
void bozo(int &a, int &b) { a = 5; b = 7; } int a,b; bozo(b,a); cout <<< a << b; //prints 7 5
|
What about a function that calls a function that calls another function?? How do we deal with that?? And yet another example...
void SQR(double &x) { x = x * x; } void POWERS(double n, double &nSquared, double &twoToN) { twoTon = pow(2.0,n); nSquared = n; SQR(nSquared); }
|
Note:
For the parameter x in SQR, you can either trace it to POWERS and then to MAIN, or you can trace it right to MAIN itself. Both have been shown to you above.
This is a function that asks the user whether to type a number and gives back the number if yes.
int ask(double &x) { char answer; do { cout << "Enter a number? (y/n) "; cin >> answer; } while (answer != 'y' && answer != 'n'); if (answer == 'y) { cout << "OK, enter it: "; cin >> x; } return answer == 'y'; }
And the call...
double s; . . . if (ask(s)) { // code that uses s };
Overloading is nothing more than using the same function name for multiple functions. Which function body is actually used is determined by number and types of actual parameters. Overloading is best used for functions that do essentially the same thing when given different types. See Demo GAA,cpp
BEWARE!!!! Overloading is a double-edged sword. It can help, but it can also be used to create deceptive code. (Not nice to deceive your graders) So please be careful!!!
To Index Previous Next