You are on page 1of 2

References

• C++ gives us a new tool – a “reference”


• A reference is like a pointer that can’t be
Intro to C++ part 6 changed.
• Recall the “swap” function:
Daniel Wigdor
void swap(int *x, int *y) {
Some material from: int store = *x;
1. Richard Watson *x = *y;
2. Winston, P.H., “On to C++” *y = store;
ISBN: 0-201-58043-8 }

From C to C++ Why Use References?


• This can be re-written with references: • References provide a subset of the
functionality of a pointer.
// old one
void swap(int *x, int *y) {
• References are easier to use &
int store = *x; understand than pointers
*x = *y;
*y = store; • No need to dereference variables
}

// new one
void swap(int &x, int &y) {
int store = x;
x = y;
y = store;
}

Basics of References Danger!!


• Declare a reference to x, called r: • Notice something wrong with that
main() {
int x = 17;
function?
int &r = x;
int &max(int x, int y) {
r = 18; if (x > y) { return x; }
cout << x << endl; else { return y; }
cout << r << endl; }
}
• A function that returns by reference: • A reference to one of x or y is returned.
int &max(int x, int y) {
When do these variables go out of scope?
if (x > y) { return x; }
else { return y; }
}

1
The Safe Version Why not always use references?

• References can never be “null”


#include <iostream.h>

int &max(int &x, int &y) {


if (x > y) { return x; } • References can never be reassigned
else { return y; }
} • Returning by reference can be dangerous.
main() {
int x = 17;
int y = 19;
int &z = max(x,y );
y = 18;
cout << x << endl; // what is output?
cout << y << endl; // what is output?
cout << z << endl; // what is output?
}

Isn’t Passing by Reference


Why Ever Pass by Reference?
Dangerous?
• Some functions require it (like swap) • Passing by reference means that any
• Others don’t – but you should consider changes made inside the function affect
using it anyway to save time & memory. the original version.
• If you pass an object the usual (“by value”) • Functions can declare that they will not
way, it is copied: change members passed by reference:
Cat max_size(Cat o, Cat t) { … Groom(const Cat &c) {
c.height = 17; // illegal
• Passing by reference makes no copy: ...
}
Cat &max_size(Cat &o, Cat &t) { …

You might also like