1. Lecture 06
Reference Variables
Learn about:
- Reference arguments
- Pass Arguments and Structures by reference
- const function arguments
Ref.: OOP using C++, Joyce Farrel, Thopson Learningv
1
2. Reference Variables (page 137-139)
• A reference is an alias (a different name) to a variable.
• How to declare a reference variable?
i) By placing a type and & in front of a variable.
ii) Assign another variable of the same type to the
reference variable.
For example: double someMoney;
double &cash = someMoney
2/11
4. Reference Arguments
• Passing arguments by reference allows a function to
access variables in the calling program, as well as
returning more than one value.
• Reference arguments are indicated by the & following
the data type.
(float n, float &intp, float &fracp)
4/11
5. Reference Arguments
Example 1
#include <iostream.h>
void intfrac(float n, float& intp, float& fracp)
{ long temp = static_cast<long>(n); // temp = 10
intp = static_cast<float>(temp); // intp = 10
fracp = n - intp; // fracp = 0.25
}
void main()
{ float number, intpart, fracpart;
do {
cout << "nEnter a real number: ";
cin>>number; // input: 10.25
intfrac(number, intpart, fracpart);
cout << "Integer part is " << intpart
<< ", fraction part is "
<< fracpart << endl;
} while( number != 0.0 );
5/11
}
6. Reference Arguments
Example 1 (cont.)
• The & indicates that intp is an alias for whatever variable is
passed as an argument. Similarly for fracp.
• Note that the & is not used in the function call.
• Do not confuse with the address of operator (same symbol).
6/11
9. Passing Structures By Reference
Example (cont.)
int main()
{
Distance d1 = { 12, 6.5 };
Distance d2 = { 10, 5.5 };
cout << "nd1 = "; engldisp(d1);
cout << "nd2 = "; engldisp(d2);
scale(d1, 0.5);
scale(d2, 0.25);
cout << "nd1 = "; engldisp(d1);
cout << "nd2 = "; engldisp(d2);
cout << endl;
return 0;
}
• By default, structures are passed by value (i.e. copy each member).
• Passing structure by reference is much more efficient.9/11
10. const Function Arguments
• Passing arguments by reference is more
efficient and also allows the function to modify
them directly.
• Can you pass an argument by reference for
efficiency, but with a guarantee that the
function cannot modify it?
• You can apply the const modifier.
10/11
11. const Function Arguments
Example
#include <iostream.h>
void main()
{
int alpha = 7;
int beta = 11;
aFunc(alpha, beta);
}
void aFunc(int& a, const int& b)
{
a = 107; // OK
b = 111; // error: can't modify const
}
11/11