Search code examples
c++referenceconstants

C++ Difference Between Const Reference to Non Const Object and Non Const Reference to Non Const Object


What is the purpose for the "const" keyword for a reference if the object it is referencing is not a const object? Is there any difference between what r1 and r2 does (below)?

int i = 42; // non const object
const int &r1 = i; // const reference to non const object

int j = 25; // non const object
int &r2 = j; // non const reference to non const object

Here's a quote from CPP Primer 5th:

"C++ programmers tend to abbreviate the phrase “reference to const” as “const reference.” This abbreviation makes sense—if you remember that it is an abbreviation. Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const. Whether a reference refers to a const or nonconst type affects what we can do with that reference, not whether we can alter the binding of the reference itself."

I think this means that making a reference a "const" when it is referenced to a non const object does absolutely nothing. We may as well take that const keyword out when defining that reference.

Asking this question here for confirmation.

Edit: Looks like my initial conjecture is wrong. I understand now that a const reference to a non const object does have a purpose: to prevent the reference from modifying the object. The non const object can still be modified by other means but not by this const reference.

Thanks all.


Solution

  • "What is the purpose for the "const" keyword for a reference if the object it is referencing is not a const object?" The purpose is to prevent that reference being used to modify the object it is referencing.

    int i = 42; // non const object
    const int &r1 = i; // const reference to non const object
    r1 = 6 * 9; // error, r1 cannot be used to modify i;