Harold Serrano

View Original

C++ tip 16: References are Aliases, not Pointers

Something that may confuse you as you start learning C++ is the belief that References are Pointers. They do kind of act the same, but references are not pointers and they do not behave like pointers.

So what is a Reference? According to Sthepen Dewhurst, A reference is another name, alias, for an EXISTING object.

Did you noticed that I capitalized EXISTING?

This is an important distinction between references and pointers. There can't be NULL references. All references require initialization and the object which it refers to must be in existence.

This is so important, so let me state it again:

A reference is an alias for an object that already exist prior to the initialization of the reference.

Let's see some examples

int i=10;
int &iRef=i; //iRef is a reference for variable i. In other words an alias

i=11;  //since i now equals 11, iRef also equals 11
iRef=9; //now i equals 9

Sthepen Dewhurst also states the following:

Once a reference is initialized to refer to a particular object, it cannot later be made to refer to a difference object; a reference is bound to its initializer for its whole lifetime.

Finally, a reference can not be initalized to a non-const literal or temporary value. For example:

int &i=10; //error!

However, a reference to const is permited:

const int &idk=12; //ok

Why is this so? Sthepen Dewhurst gives a great insight into this:

When a reference to const is initialized with a literal, the reference is set to refer to a temporary location initialized with the literal. Thus, idk does not refer to 12 but to a temporary location of type int initialized with 12. Normally, such temporary location will be destroyed once they go out of scope. However, when such temporary is used to initialized a reference to const, the temporary will exist as long as the reference that refers to it.

So keep this tip in mind:

References are aliases, not Pointers

Sign up to my newsletter to get tips on Game Engine Development and C++.