Example: References as Function Parameters
Okay. I think I'm getting it.
Great!
But why are we doing this? Why do we want multiple names for the same data?
Yeah, why not just use the name we already gave it?
You're right. In these simple examples it does seem kind of silly. But references are a really important capability!
This example will illustrate an important use of references.
void spotTransplant(Cow donor, Cow recipient) {
size_t donorSpots = donor.getNumSpots();
size_t recipientSpots = recipient.getNumSpots();
recipient.setNumSpots(donorSpots + recipientSpots);
donor.setNumSpots(0);
}
int main() {
Cow buttercup{1, 3}; // Cow(size_t numSpots, size_t age)
Cow flopsy{2, 13};
spotTransplant(flopsy, buttercup);
cout << buttercup.getNumSpots() << " "
<< flopsy.getNumSpots();
}
Notice that we are using objects here (of type Cow
). We'll talk more about classes and objects soon, but for now you can see some familiar syntax for using objects.
What do you think this program will print?
Hints:
- Imagine what the diagram will look like.
- The
Cow
s will follow the same diagram rules that we've used for everything else.
Key Idea: Without the ability to give a piece of data two names, a function can't alter data outside of its own stack frame!
Which would make object-oriented programming impossible!
Now consider this change to the example.
Only two characters have changed! They are highlighted in yellow.
void spotTransplant(Cow& donor, Cow& recipient) {
size_t donorSpots = donor.getNumSpots();
size_t recipientSpots = recipient.getNumSpots();
recipient.setNumSpots(donorSpots + recipientSpots);
donor.setNumSpots(0);
}
int main() {
Cow buttercup{1, 3};
Cow flopsy{2, 13};
spotTransplant(flopsy, buttercup);
cout << buttercup.getNumSpots() << " "
<< flopsy.getNumSpots();
}
Key Idea: Taking references as parameters allows a function to alter data outside of its own stack frame.
This is cool!
Yes, it means we can do OOP after all!
(When logged in, completion status appears here.)