Behrooz Karjoo
Behrooz Karjoo

Reputation: 4292

operator == overloading function fails

I am overloading operators > < == in a simple time class.

double exchange_time::seconds_from_midnight() const {
    return seconds + minutes * 60.0 + hours * 3600.0 + milliseconds / 1000.0;
}

bool exchange_time::operator<(const exchange_time& other) const
{
    return seconds_from_midnight() < other.seconds_from_midnight();
}

bool exchange_time::operator>(const exchange_time& other) const
{
    return seconds_from_midnight() > other.seconds_from_midnight();
}

bool exchange_time::operator==(const exchange_time& other) const
{
    return seconds_from_midnight() == other.seconds_from_midnight();
}

The > and < work perfect. However the == yields false and my test fails:

TEST_F(exchange_time_test, comparison) {
    exchange_time et1, et2;
    et1.set("93500001");
    et2.set("93500123");
    EXPECT_TRUE(et2 > et1);
    EXPECT_TRUE(et1 < et2);
    EXPECT_TRUE(et2 == et2);
}

Is there something I'm missing ?

Here's my declaration:

class exchange_time {
    public:
        void set(string timestamp);
        unsigned short int get_milliseconds() { return milliseconds; }
        unsigned short int get_seconds() { return seconds; }
        unsigned short int get_minutes() { return minutes; }
        unsigned short int get_hours() { return hours; }
        double seconds_from_midnight() const;
        bool operator<(const exchange_time& other) const;
        bool operator>(const exchange_time& other) const;
        bool operator==(const exchange_time& other) const;
    private:
        unsigned short int milliseconds;
        unsigned short int seconds;
        unsigned short int minutes;
        unsigned short int hours;
};

Upvotes: 0

Views: 88

Answers (1)

Shakil Ahamed
Shakil Ahamed

Reputation: 577

Never compare equality for double numbers. Check if they are almost equal. The most common way is to use an epsilon to compare the values.

bool exchange_time::operator==(exchange_time other)
{
  return abs(seconds_from_midnight() - other.seconds_from_midnight()) < EPS;
}

Where EPS is a very small value. If you need accurate comparison, you need to define your own Fraction class.

EDIT
EPS stands for Epsilon, which is defined as A very small, insignificant, or negligible quantity of something by Dictionary.com.

Upvotes: 4

Related Questions