Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Constant References And Immutability | References
C++ Smart Pointers
course content

Course Content

C++ Smart Pointers

C++ Smart Pointers

1. Introduction to Smart Pointers
2. Unique Pointers
3. Shared Pointers
4. Weak Pointers
5. References
6. Advanced topics

bookConstant References And Immutability

A constant reference is a special type of reference that cannot be used to change the value of the referenced object. It provides a level of immutability, i.e. it ensures that the data remains constant within the scope of the reference. Let’s consider an example for better understanding:

cpp

main

copy
12345678910
int main() { int var = 42; // Const reference to value const int& ref = var; // Uncomment to get compilation error: Cannot modify through a const reference // ref = 10; }

In the above code, we create a constant reference by using the const keyword. Once we have done that, we can’t modify the value of the referenced variable (var in our case) using that reference. You can test this by uncommenting the ref = 10; line to get a compilation error.

Benefits of immutability

Immutable code has several advantages. It enhances code readability and simplifies debugging; when someone sees that a variable has been declared to be constant, they can be sure that its value is not going to change anywhere. It also decreases compilation overhead, as the compiler doesn’t have to worry about the value mutations of a constant reference.

Const references as function parameters

One of the most powerful use cases of constant references is passing them as function parameters to avoid unnecessary copies and ensure data integrity. Here’s how it works:

  • Since a reference is just an alias of the original variable, there is no copying involved.

  • Since we set the reference to constant, the function can’t modify the value of the reference. This ensures that the function only gets read-only access to the variable.

Since the purpose of the displayInfo function is to display the message, not update it, we use a constant reference to pass message to it. This way, the function can’t update the value of message.

As a general rule, try to use constant references across all functions in your code, unless you need to modify the variable inside the function.

The following code defines a reference to an integer variable. Modify the code to make it a constant reference.

The following code defines a reference to an integer variable. Modify the code to make it a constant reference.

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt