Chapter 3. References

Table of Contents

The Concept Behind Reference
Reference in earlier programming languages
Scope and Life Rules
Return type
Examples for Reference return type
Difference between Reference and Pointer
Parameter Passing
Proxy objects

What is the concept behind reference? Left values. What is the difference between pointers and references? Parameters passed by reference, functions returning reference. Constant reference. Reference and polymorphism.

The Concept Behind Reference

In modern programming languages there is two important concepts defining the behaviour of variables:

  • Scope: Defines the area in the program source where a certain identifier binded to a memory location. Also defines the visibility: when the identifier is valid to use and means the memorylocation we mentioned before.

  • Life: Defines the time-span under runtime when the memory location is safe to store our values. After the duration the memory location is not safe to access.

Most cases we define scope and life in the same declaration:

// 1. allocates memory for an int type variable (in the stack)
// 2. binds the name "i" to this memory area.

int i;

Sometimes we can define a memory location, without binding a name to it.

// 1. allocates memory for an int type variable (in the heap)
//    no name has been bound to this memory

new int;

And sometimes we can bind a new name to an existing memory location, whether a name has been already binded to it or not.

// 2. binds the name "j" to memory area already called "i"

int &j = i;