References
Objectives
We would like to :
- Understand reference variables in C++
Notes
- This is partially from page 84 in your book.
- To be able to implement ++ we need to understand reference variables.
- Remember
- A regular variable is the memory address where the data is stored.
- the data at a regular variable is the data
- A pointer variable holds the address of an address where data is stored.
- The data at a pointer is an address
- This address is where the actual data is stored.
- Pointers, among other things, allow us to access dynamic memory.
- But that is for the future.
- Review pass by reference and pass by value
- In pass by value, the data is copied from the argument to the parameter.
- In pass by reference, the address of the parameter is copied to the reference.
- So in a very real sense, a reference is a pointer
- BUT it behaves differently.
- On the first assignment, the address of the target is copied
- IE it acts as a raw pointer.
- After that, the pointer is (automatically) dereferenced, and the argument is accessed.
- For this reason, references are sometimes called aliases or nicknames.
- The cool part is, reference are available for other uses.
- When declaring a reference, it must be initialized.
- IE it must be set equal to another memory location.
- And the thing it points to can not change after that.
- But the value at the thing it points to can!
- We need to be careful
- A reference is not a pointer.
- It may not be implemented this way.
- But it is a reasonable way to think about it.
- Look at referenceStart.cpp, we can clearly see that a and b are pointing to the same memory location.
- The book points out that references can alleviate the need for pointer notation.
- We can point the reference at the address stored in the pointer.
- We need to be careful here, see the example.
- So why are we discussing this now?
- We have already seen that some functions return a reference
-
ostream & operator <<(ostream & s, const DataT & other);
- If you recall at the end we just
return s
- This should make sense now.
- We also need it for the ++, += and other operators like this.
- And that is for the next set of notes.
- This is not all on references
- They have different interactions with classes.
- But that is for another day.