Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Reference Use Cases | References Fundamentals
C++ Pointers and References
course content

Course Content

C++ Pointers and References

C++ Pointers and References

1. Pointers Fundamentals
2. Pointer Arithmetic
3. References Fundamentals
4. Dynamic Memory Allocation

bookReference Use Cases

References provide a powerful mechanism for working with functions. Similar to pointers they enable a direct connection between the caller and the called function, allowing for efficient parameter passing and modification of variables.

Pass-by-reference

This involves passing the actual reference to the variable rather than its value. This allows functions to directly manipulate the original variables.

Look at the example of this implementation, but with the usage of pointers.

cpp

main

copy
12345678910111213
#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = &num; increment(p_num); std::cout << "Original value: " << num << std::endl; }

Everything functions properly, but failing to assign an address to the pointer or passing a nullptr to the function could result in errors.

cpp

main

copy
12345678910
#include <iostream> void increment(int& num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }

Reference Variable as Alias

A reference is like a nickname for a variable. It lets you access the variable using a simpler name, making your code easier to understand, while also avoiding unnecessary memory overhead.

cpp

main

copy
123456789101112
#include <iostream> int main() { float temperature_outside = 67.2; const float& thermostat = temperature_outside; temperature_outside += 15.7; std::cout << thermostat << std::endl; std::cout << temperature_outside << std::endl; }

Any modifications made to the temperature_outside variable will be reflected in the thermostat reference. However, attempts to alter the value through the thermostat reference itself are restricted due to the use of the const qualifier.

This approach provides a secure method for retrieving temperature readings using the thermostat reference while retaining the ability to update the temperature_outside variable.

What is the purpose of a reference in C++?

What is the purpose of a reference in C++?

Select a few correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

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