I have a class MyCloth
and one one object instance of that class that I instantiated like this:
MyCloth** cloth1;
And at one point in the program, I will do something like this:
MyCloth** cloth2 = cloth1;
And then at some point later, I want to check to see if cloth1
and cloth2
are the same. (Something like object equality in Java, only here, MyCloth
is a very complex class and I can''t build an isEqual
function.)
How can I do this equality check? I was thinking maybe checking if they point to the same addresses. Is that a good idea? If so, how do I do that?
You can test for object identity by comparing the addresses held by two pointers. You mention Java; this is similar to testing that two references are equal.
MyCloth* pcloth1 = ...
MyCloth* pcloth2 = ...
if ( pcloth1 == pcloth2 ) {
// Then both point at the same object.
}
You can test for object equality by comparing the contents of two objects. In C++, this is usually done by defining operator==
.
class MyCloth {
friend bool operator== (MyCloth & lhs, MyCloth & rhs );
...
};
bool operator== ( MyCloth & lhs, MyCloth & rhs )
{
return ...
}
With operator== defined, you can compare equality:
MyCloth cloth1 = ...
MyCloth cloth2 = ...
if ( cloth1 == cloth2 ) {
// Then the two objects are considered to have equal values.
}