I have an overloaded assignment operator function. Within the function I have a self-assessment check that does not seem to work as expected.
I've spent the whole day trying to figure out what the problem is. I am able to successfully get the self-assessment check to work properly when I write a entirely new code on my own but I am not able to determine where the problem is here in this particular code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(){
Contact c("Empty Contact", 3);
c.display();
cout << "Enter Contact information: " << endl;
c.read();
c.display();
cout << "Please wait";
for (int i = 0; i < 1000000; i++){
Contact cp = c;
c = cp;
if (!(i % 100000)) cout << ".";
}
cout << endl;
c.display();
system("pause");
return 0;
}
This is where the self-assessment check is located.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Contact& Contact::operator=(const Contact& source) {
if (this == &source) { //this condition is always false
return *this;
}
else {
delete[] _pn;
for (int i = 0; i < 41; i++)
_name[i] = source._name[i];
_pn = new PhoneNumber[source._noPN];
for (int i = 0; i < source._noPN; i++)
_pn[i] = source._pn[i];
return *this;
}
}
I made a typo, sorry. What I mean't is self-assessment. In the 2nd line of the 2nd code, the condition "this == &source" always results in false. I don't understand why this condition would result in false when the values of the variables of both objects are the same.
This is how I have the copy constructor written which is called first before the assignment operator function is called.
1 2 3 4 5 6 7 8 9 10 11 12
Contact::Contact(const Contact& source) {
if (source.isEmpty()) {
setEmpty();
}
else {
strcpy_s(_name, source._name); // not sure if this is correct
_name[40] = '\0';
_pn = new PhoneNumber[source._noPN];
for (int i = 0; i < source._noPN; i++)
_pn[i] = source._pn[i];
}
}
I made a typo, sorry. What I mean't is self-assessment. In the 2nd line of the 2nd code, the condition "this == &source" always results in false. I don't understand why this condition would result in false when the values of the variables of both objects are the same.
Because it doesn't compare equality. It compares the addresses of the objects.