A compound type is a type that is defined in terms of another type. C++(www.cppentry.com) has several compound types, two of which—references and pointers—we’ll cover in this chapter.
Defining variables of compound type is more complicated than the declarations we’ve seen so far. In § 2.2 (p. 41) we said that simple declarations consist of a type followed by a list of variable names. More generally, a declaration is a base type followed by a list of declarators. Each declarator names a variable and gives the variable a type that is related to the base type.
The declarations we have seen so far have declarators that are nothing more than variable names. The type of such variables is the base type of the declaration. More complicated declarators specify variableswith compound types that are built from the base type of the declaration.
2.3.1 References
The new standard introduced a new kind of reference: an “rvalue reference,” which we’ll cover in § 13.6.1 (p. 532). These references are primarily intended for use inside classes. Technically speaking, when we use the term reference, we mean “lvalue reference.”
A reference defines an alternative name for an object. A reference type “refers to” another type. We define a reference type by writing a declarator of the form &d, where d is the name being declared:
- int ival = 1024;
- int &refVal = ival;
- int &refVal2;
Ordinarily, when we initialize a variable, the value of the initializer is copied into the object we are creating. When we define a reference, instead of copying the initializer’s value, we bind the reference to its initializer. Once initialized, a reference remains bound to its initial object. There is no way to rebind a reference to refer to a different object. Because there is no way to rebind a reference, references must be initialized.
A Reference Is an Alias
A reference is not an object. Instead, a reference is just another name for an already existing object.
After a reference has been defined, all operations on that reference are actually operations on the object to which the reference is bound:
- refVal = 2;
- int ii = refVal;
When we assign to a reference, we are assigning to the object to which the reference is bound. When we fetch the value of a reference, we are really fetching the value of the object to which the reference is bound. Similarly, when we use a reference as an initializer, we are really using the object to which the reference is bound:
-
- int &refVal3 = refVal;
-
- int i = refVal;
Because references are not objects, we may not define a reference to a reference.