infinitloop infinitloop - 3 months ago 9
C++ Question

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


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 why i am assuming it is a pointer notation because this is a pointer after all and we are checking for equality of two pointers.
Thanks.

Answer

To start, note that

this

is a special pointer ( == memory address) to the class its in. First, an object is instantiated:

CDummy a;

Next, a pointer is instantiated:

CDummy *b;

Next, the memory address of a is assigned to the pointer b:

b = &a;

Next, the method CDummy::isitme(CDummy &param) is called:

b->isitme(a);

A test is evaluated inside this method:

if (&param == this) // do something

Here's the tricky part. param is an object of type CDummy, but &param is the memory address of param. So the memory address of param is tested against another memory address called "this". If you copy the memory address of the object this method is called from into the argument of this method, this will result in true.

This kind of evaluation is usually done when overloading the copy constructor

MyClass& MyClass::operator=(const MyClass &other) {
    // if a programmer tries to copy the same object into itself, protect
    // from this behavior via this route
    if (&other == this) return *this;
    else {
        // otherwise truly copy other into this
    }
}

Also note the usage of *this, where this is being dereferenced. That is, instead of returning the memory address, return the object located at that memory address.

Comments