Realizing underlying implementation and restrictions
References can ease the notation required for indirect referencing. However, there are situations in which references simply cannot take the place of pointers. To understand these situations, it is useful to review the underlying implementation of a reference in C++.
References are implemented as constant pointers, hence they must be initialized. Once initialized, references may not refer to a different object (though the value of the object being referenced can be changed).
To understand the implementation, let’s consider a sample reference declaration: int &intVar = x;
. From an implementation aspect, it is as though the former variable declaration is instead declared as int *const intVar = &x;
. Note that the &
symbol shown on the left-hand side of an initialization takes on the meaning of reference, whereas the &
symbol shown on the right-hand side of an initialization or assignment implies address...