Session 19 of Software Lessons, “Programming in C++: Pass by Reference, Pointer and Value Part 2,” runs about 24 minutes.
What this session covers
- Pass by reference, pass by pointer and pass by value
- Legal and illegal variants of each
- The reasoning behind the rules
Key ideas
- Pass by value gives the function its own copy, so changes inside the function do not affect the caller.
- Pass by reference gives the function another name for the caller’s object, so changes are visible to the caller and no copy is made.
- Pass by pointer passes the address of the object, and the function must dereference it; a pointer can also be null.
- Copying large objects is costly, which is why passing by reference or by const reference is common.
- Choosing between the three comes down to whether the function should modify the original, whether the argument may be absent, and how expensive a copy is.