how does the ampersand(&) sign work in c++?

infinitloop picture infinitloop · Jan 13, 2012 · Viewed 84.5k times · Source

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?

This is confusing me:

class CDummy 
{
public:
   int isitme (CDummy& param);
};

int CDummy::isitme (CDummy& param)
{
  if (&param == this)
  { 
       return true; //ampersand sign on left side??
  }
  else 
  {    
       return false;
  }
}

int main () 
{
  CDummy a;
  CDummy* b = &a;

  if ( b->isitme(a) )
  {
    cout << "yes, &a is b";
  }

  return 0;
}

In C & usually means the address of a var. What does it mean here? Is this a fancy way of pointer notation?

The reason I am assuming it is a pointer notation because this is a pointer after all and we are checking for equality of two pointers.

I am studying from cplusplus.com and they have this example.

Answer

Luchian Grigore picture Luchian Grigore · Jan 13, 2012

The & has more the one meanings:

1) take the address of a variable

int x;
void* p = &x;
//p will now point to x, as &x is the address of x

2) pass an argument by reference to a function

void foo(CDummy& x);
//you pass x by reference
//if you modify x inside the function, the change will be applied to the original variable
//a copy is not created for x, the original one is used
//this is preffered for passing large objects
//to prevent changes, pass by const reference:
void fooconst(const CDummy& x);

3) declare a reference variable

int k = 0;
int& r = k;
//r is a reference to k
r = 3;
assert( k == 3 );

4) bitwise and operator

int a = 3 & 1; // a = 1

n) others???