Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification of References in C++

So I am attempting to learn C++ and I have come across something that puzzles me slightly. I have the code,

int x = 0;
int &y = x;
cout << &x<< " " << x << " " << &y << " " <<y<< endl;

This compiles fine and results in:

0 003AFA08 0 003AFA08

What I have trouble understanding why the conversion of x, an int, to &y, a reference, doesn't result in an error. At first I thought it was some sort of conversion however,

int &y = &x;

results in an error.

Can anyone explain why this works in this way? Thanks in advance.

like image 707
Daniel Gratzer Avatar asked Dec 26 '11 05:12

Daniel Gratzer


1 Answers

int& is not an address. It is a reference.

int& y = x; declares y as a reference to x. It effectively means that y becomes another name for x. Any time you use y, it is as if you had said x.

Pointers (not references) are used to store addresses. int& y = &x; is not valid because &x is the address of x (it's an int*). y is a reference to an int, not a reference to an int*.

like image 162
James McNellis Avatar answered Oct 20 '22 02:10

James McNellis