Creating a Reference

You create a reference by writing the type of the target object, followed by the reference operator (&), followed by the name of the reference. References can use any legal variable name, but for this book we'll prefix all reference names with r. So, if you have an integer variable named someInt, you can make a reference to that variable by writing the following:

int &rSomeRef = someInt;

This is read as “rSomeRef is a reference to an integer that is initialized to refer to someInt.” Listing 11.1 shows how references are created and used.

The reference operator (&) is the same symbol as the one used for the address of the operator.


Listing 11.1. Creating and Using References
 0:  //Listing 11.1
 1:  // Creating and Using References
 2:  #include <iostream>
 3:
 4:  int main()
 5:  {
 6:      int  intOne;
 7:      int &rSomeRef = intOne;
 8:
 9:      intOne = 5;
10:      std::cout << "intOne: " << intOne << std::endl;
11:      std::cout << "rSomeRef: " << rSomeRef << std::endl;
12:
13:      rSomeRef = 7;
14:      std::cout << "intOne: " << intOne << std::endl;
15:      std::cout << "rSomeRef: " << rSomeRef << std::endl;
16:      return 0;
17:  }


intOne: 5
rSomeRef: 5
intOne: 7
rSomeRef: 7
					

On line 6, a local int variable, intOne, is declared. On line 7, a reference to an int, rSomeRef, is declared and initialized to refer to intOne. If you declare a reference but don't initialize it, you will get a compile-time error. References must be initialized.


On line 9, intOne is assigned the value 5. On lines 10 and 11, the values in intOne and rSomeRef are printed, and are (of course) the same, because rSomeRef is simply the reference to intOne.

On line 13, 7 is assigned to rSomeRef. Because this is a reference, it is an alias for intOne, thus the 7 is really assigned to intOne, as is shown by the display on lines 14 and 15.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.103.206