Pointers can be reused as long as the type is the same (or co-linear). Once a reference is assigned it is not possible to make it “point” to a new variable. Typically this will result in an assignment of the value of the new variable to the old variable:

int a = 5;
int b = 6;
int & intRef = a;
intRef = 4; // -> a == 4
intRef = b; // -> a == 6

This is a very contrived example, but when you start getting classes (e.g. containers) that return references this sort of thing can happen:

// Prototype for container method GetElement
Element & ContainerType::GetElement(size_t index);

// Usage
Element & elementRef = container.GetElement(1); // elementRef points to the element at index 1
// ...
// do things with the ref
// ...
elementRef = container.GetElement(5); // elementRef does not point to element at index 5 - rather element 5 is assigned to element1 (using a default assignment operator, if necessary)
Coding Hint for the Day #1: Do not attempt to re-assign references
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.