I have a class MyCloth
and one one object instance of that class that I instantiated like this:
MyCloth** cloth1;
And at one p
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.
}
If you would like to define a method by which to order a comparison of a set of objects of your custome class. For example:
someClass instance1;
someClass instance2;
You can do so by overloading the < operator for this class.
class someClass
{
bool operator<(someClass& other) const
{
//implement your ordering logic here
}
};
If what you want to do is compare, and see if the objects are literally the same object, you can do a simple pointer comparison to see if they point to the same object. I think your question is poorly worded, I'm not sure which you're going for.
EDIT:
For the second method, it's really quite easy. You need access to the memory location of your object. You can access this in many different ways. Here are a few:
class someClass
{
bool operator==(someClass& other) const
{
if(this == &other) return true; //This is the pointer for
else return false;
}
};
Note: I do not like the above, as usually == operators go more in depth than just comparing pointers. Objects can represent objects of similar qualities without being the same, but this is an option. YOu can also do this.
someClass *instancePointer = new someClass();
someClass instanceVariable;
someClass *instanceVariablePointer = &instanceVariable;
instancePointer == instanceVariable;
This is non-sensical and invalid/false. If it would even compile, depending on your flags, hopefully your using flags that wouldn't allow this!
instancePointer == &instanceVariable;
This is valid and would result in false.
instancePointer == instanceVaribalePointer;
This is also valid and would result in false.
instanceVariablePointer == &instanceVariable;
This is also valid and would result in TRUE
instanceVariable == *instanceVariablePointer;
This would use the == operator we defined above to get the result of TRUE;