Reference Definitions
We can define multiple references in a single definition. Each identifier that is a referencemust be preceded by the & symbol:
- int i = 1024, i2 = 2048; // i and i2 are both ints
- int &r = i, r2 = i2; // r is a reference bound to i; r2 is an int
- int i3 = 1024, &ri = i3; // i3 is an int; ri is a reference bound to i3
- int &r3 = i3, &r4 = i2; // both r3 and r4 are references
With two exceptions that we’ll cover in § 2.4.1 (p. 61) and § 15.2.3 (p. 601), the type of a reference and the object to which the reference refersmust match exactly. Moreover, for reasons we’ll explore in § 2.4.1, a referencemay be bound only to an object, not to a literal or to the result of a more general expression:
- int &refVal4 = 10; // error: initializer must be an object
- double dval = 3.14;
- int &refVal5 = dval; // error: initializer must be an int object