CS 70

Example: Why const References?

  • Horse speaking

    Whoah, wait a second. A reference is mostly useful for letting a function alter data outside of its scope.

  • LHS Cow speaking

    Yes.

  • Horse speaking

    And a const reference… doesn't let you alter its data?

  • LHS Cow speaking

    Yes?

  • Horse speaking

    So, why would we want a const reference??

  • LHS Cow speaking

    Oh, right! Let's take a look at an example.

In the code snippet below, let's suppose we have an Elephant class we're working with. We don't need to flesh out all the details, but we'll imagine it has lots of useful methods and that an elephant object requires quite a lot of memory (after all, elephants are large and they purportedly never forget!).

bool isJuvenile(Elephant e) {
    return e.age() >= 5 && e.age() < 10;
}

int main() {
    Elephant nelly{"Nelly", 17, false, true};
    cout << isJuvenile(nelly) << endl;
}

Think about what the stack looks like when isJuvenile starts running. (It will help you answer the question below!)

Do you see anything you don't like about this snippet of code?

Key Points:

  • Passing a parameter by reference prevents unnecessary copy operations.

  • When a function takes a const reference as a parameter, it promises not to change the value of what is passed in.

  • RHS Cow speaking

    That way we get the safety of passing in a copy (can't change the original) without doing the work of actually making a copy.

(When logged in, completion status appears here.)