Overloading operators

Hi Guys,
Just got a quick question on over loading the les than < operator.

I'm trying write some code to ask a generic class member if its less than a certain argument.

I found this code on line and i've changed it a little and would like to know if it would work.

It had the object "this" is that a correct object?
will it automatically change the object being sent the request and copy it to "this" to compare?

Here's the code

bool date::operator<(const date &rhs)const
{
// Check for self-assignment!
if (this < &rhs) // less than object?
return 1; // .
else
{


return 0;
}

}

If not could some one please let me know of a way I could ask anf class objest if is lees than the reference?

Any help greatly appreciated.

regards
Brendan

This operator compares the location of the objects in the virtual address space. Although it's possible that such a comparison might be useful in some cases, it's probably not what you want.

The comment "Check for self-assignment" is not correct. This is not an assignment operator, but comparison. The code was probably copied from an assignment operator and modified.

The return values should be true and false, instead of 1 and 0.

You should probably implement a better comparison function based on the value of the "date" object instead of the address. depending on how the date class is implemented e.g.

1
2
3
4
5
6
7
8
9
10
bool operator<(const date& rhs) const {
  if (year < rhs.year)
    return true;
  else if (month < rhs. month)
    return true;
  else if (day < rhs.day)
    return true;
  else
    return false;
}

Correction: The draft implementation above is wrong, it should be:
1
2
3
4
5
6
7
8
9
10
bool operator<(const date& rhs) const {
  if (year != rhs.year)
    return year < rhs.year;
  else if (month != rhs. month)
    return month < rhs. month;
  else if (day != rhs.day)
    return day < rhs.day;
  else
    return false; // equal
}
Topic archived. No new replies allowed.