Example: Why const
References?
Whoah, wait a second. A reference is mostly useful for letting a function alter data outside of its scope.
Yes.
And a
const
reference… doesn't let you alter its data?Yes?
So, why would we want a
const
reference??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!)
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.
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.)