why do we Check for self-assignment during the overloading of assignment operator ???
means
Cents& Cents::operator= (const Cents &cSource)
{
// check for self-assignment by comparing the address of the
// implicit object and the parameter
if (this == &cSource)
return *this;
For trivial assignment operators like that... it really doesn't matter whether you do it or not. In fact... you probably don't even need to write that assignment operator... as the compiler-provided default will do the same.
For more complicated assignment operators, it prevents you from freeing memory or destroying resources you are still using. Example:
class Foo
{
int* dynamicdata;
int size;
public:
Foo(int s)
{
size = s;
dynamicdata = newint[size];
}
~Foo()
{
delete[] dynamicdata;
}
Foo& operator = (const Foo& rhs)
{
if(this == &rhs) return *this; // <- now this is very important!
size = rhs.size;
delete[] dynamicdata;
dynamicdata = newint[size];
std::copy( /*... copy stuff from rhs.dynamicdata to dynamicdata ...*/ );
return *this;
}
};
Without checking for self assignment... the delete[] on line 22 would delete our buffer! This would destroy the data for this object.
Normally that's okay because we're replacing that data with data obtained from the 'rhs' object... but if that 'rhs' object is the same as this one... then we've just destroyed that data!