Question about declarations using the reference operator in a declaration

I read through this page in your tutorial to brush up on pointers

http://www.cplusplus.com/doc/tutorial/pointers/

and I understood it all very well. Then I came across this piece of code on this website: http://www.4p8.com/eric.brasseur/cppcen.html (no. 8)

1
2
3
4
5
6
7
8
9
10
11
12
int main ()
{
   double a = 3.1415927;

   double &b = a;                            // b is a

   b = 89;

   cout << "a contains: " << a << endl;     // Displays 89.

   return 0;
}


I don't understand what is happening on the second line in main()'s code block. Without reading the entire program, I would assume the following:

&b is the address in memory for b. So the address of b is now the value 3.1415927.

Can you do that? Don't memory addresses have certain formats (not double)?

Reading the rest of the program, it appears that this didn't happen. Instead b and a are the same variable.

Can someone explain what the compiler is doing here and how it's parsing the code?
Last edited on
Here b is of the type double &, that is a double reference. It's very similar to a pointer accept it doesn't need to be dereferenced.

1
2
3
4
5
6
7
8
9
10
11
12
13
//same example with pointers
int main ()
{
   double a = 3.1415927;

   double *b = &a; // b is the address of a

   *b = 89; //dereference b and store 89

   cout << "a contains: " << a << endl; // Displays 89.

   return 0;
}
Last edited on
Thank you for the reply. I'm afraid I don't understand it. What exactly is the type double &?
It's a double, but instead of it referring to a value it refers to a reference...
1
2
3
4
double a = 3.14; //good
double b = a; //copies a and stores it in b
double &c = b; //c is a reference to b
double &d = 2.8; //will not work 
Last edited on
Thank you for your replies. I think I understand what's happening. It's confusing that the syntax means one thing in the body of code, and another thing when used in a variable declaration.
Topic archived. No new replies allowed.