CS 70

Example: References as Function Parameters

  • Cat speaking

    Okay. I think I'm getting it.

  • LHS Cow speaking

    Great!

  • Cat speaking

    But why are we doing this? Why do we want multiple names for the same data?

  • Duck speaking

    Yeah, why not just use the name we already gave it?

  • LHS Cow speaking

    You're right. In these simple examples it does seem kind of silly. But references are a really important capability!

  • RHS Cow speaking

    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 Cows will follow the same diagram rules that we've used for everything else.

Make an educated guess: what do you think this program will print?

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!

  • LHS Cow speaking

    Which would make object-oriented programming impossible!

  • RHS Cow speaking

    Now consider this change to the example.

  • LHS Cow speaking

    Only two characters have changed! They are highlighted in yellow.

The two changes in the following code snippet are the addition of `&`s in the first line of code. I think that Julie just had the rendered code here, with the addition of some code to highlight those changes.
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();
}

What do you think this program will print?

Key Idea: Taking references as parameters allows a function to alter data outside of its own stack frame.

  • Dog speaking

    This is cool!

  • LHS Cow speaking

    Yes, it means we can do OOP after all!

(When logged in, completion status appears here.)