Search code examples
c++const-reference

Why a reference is likely as an object?


Currently learning c++ and nowhere else better to ask something than to the experts of S.O. I Couldn't find more complete and better answers than here. So there it goes.

DWORD dw = 5;
cout << &dw;

Displays the address where the value of dw is stored.

But then why:

void Display(  DWORD &dwUserId )
{
    cout << dwUserId;
}

int _tmain( int argc, _TCHAR* argv[] )
{
    DWORD dw = 5;
    Display( dw );
} 

Why on this example it is displayed the value of dw and not dw address?


Solution

  • & has two different meanings in this context:

    • placed in a declaration, it means the variable is a reference. In your case, you pass the parameter by reference.

    • outside a declaration, before a variable, it takes its address.

    Besides these, it can also mean the bitwise AND operator

    int x;
    int& y = x;  //y is a reference to x
    int* z = &x; //& takes the address of x and assigns it to z
    y & x;       //bitwise AND