I have a question about my C++ homework. I am just confused about *this.
The code below is what I have.
My question is why the condition in the if statement in the = operator is true?
#include <cstring>
class abc {
char p[9];
int inc;
public:
abc( ) { inc = 8; strcpy(p, "10010101"); }
~abc( );
abc& operator=(const abc &);
};
abc::~abc( ) {
}
abc& abc::operator=(const abc &c) {
if(this != &c) { //my question is why this condition is true?
inc = c.inc - 2;
for(int i=0; i<inc; i++) {
p[i] = c.p[i] + 2;
}
}
return *this;
}
int main( ) {
abc x, y;
x = y;
return 0;
}
because you don’t want to make a copy if you are assigning to yourself, that is the reason for the
ifcondition,*thisreturns self instance. It is true because you are trying to assigny to xand as they are both different instances you then make acopyofy to x.