Constant references

The reference used so far allows you to change the variable it is an alias for, therefore it has lvalue semantics. There are also const lvalue references, that is, a reference to an object that you can read, but not write to.

As with const pointers, you declare a const reference using the const keyword on a lvalue reference. This essentially makes the reference read-only: you can access the variable's data to read it, but not to change it.

    int i = 42;     const int& ri = i;     ri = 99;           // error!

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.