Reference Parameter
The C Language does not have references; it requires using Pointer parameters to make changes “propagate back” to the calling environment.
A reference is just an alias for another variable name.
In C++, we added reference parameters, which can be used for function arguments by adding &
.
Use references whenever possible in C++
References are a C++ feature that are not in C. They are like pointers but less error-prone. We recommend you use references rather than pointers wherever possible.
Using references rather than values is also more space efficient, since you need copy the whole object onto the runtime stack, just a reference to it.
Be careful with references in Queues!
If you make references to things in a queue and those get popped, then it will become a dangling reference, which can lead to undefined behavior.
- Many C++ systems started out life as a C system (and/or being developed by C programmers), so you will often see this style (ptr params) in industrial C++ code
C++ Reference Syntax
Similar to Pointer syntax, the preferred syntax in C++ for references
int& a
. Do that at interviews and in practice.
Resources
Difference between references and Pointers?
- You cannot have null references (but you can have
nullptr
)- Once a reference is initialized to an object, it cannot be changed to refer to another object (pointers can point to another object at any time)
- References must be initialized when it is created (pointers can be initialized at any time).
Passing by Value vs Passing by Reference
Swapping with pointers using a call-by-value, see Pointer. Swapping using Reference Parameters:
Use Cases
In C++, we can use normal variables as references, often to give a more convenient name to something long.
const reference parameter
Sometimes, we make the reference parameter a const
so that the reference parameter inside the function doesn’t change (compiler will prevent you from doing so).
Reference Binding
Had asked this question to myself in CS247. When you do something like this:
Does it call operator=
, or does it call a copy constructor for example? Obviously not, because you are declaring br1
as a reference. This simply does reference binding.
Types of References
oh god, this is where it gets complicated.
https://www.scaler.com/topics/cpp/pointers-vs-references-in-cplusplus/
References in C++ can be categorized based on the type of variables they can refer to such as lvalue references and rvalue references. Additionally, we can also have constant references in C++ which provides immutability.