I am trying to override the == operator for a class, however the comparison seems to failing somehow. when I write the same as a function called eq(for example) no problem occurs.
class geo
{
...
bool operator==(geo const& other)
{
if(_id != other._id) return false;
if(!(name == other.name))return false;
if(is_primary!=other.is_primary)return false;
for(int i = 0; i<6;i++){
if(position[i]!=other.position[i])
return false;
}
return true;
}
....
private:
int _id, is_primary;
vector position;
string name;
}
In main function: ...
geo* i= new geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
geo* j= new geo(2.1, 2.82, 1, 0, 0, 180, 0, "Patient-1",1);
if(i==j)
std::cout<<"they are equal\n";
However when I run this, it says they are different for i and j. Any idea of where i do the stuff wrong ?
Edit: Thank you guyz at the comments. I just solved it; the code shown above works pretty ok. If course I was trying to simplify the code to make here paste something readable. So I am updating the code above to turn it into a problem so that future readers might see a better solution than I did, as well as I can learn more.
By doing i == j
you are comparing two pointers to geo
, and not the objects they are pointing to. Since the pointers are obviously different, you get the result as such.
To actually compare objects, you need to dereference the pointers:
if (*i == *j)
`