andrew
andrew

Reputation: 83

Overloading == operator C++

i did an overloading of the + operator but now i wanna do overloading of == operator of 2 lengths (may or may not be the same length) and return the respective results. How do i do it? Do i need to use bool for ==?

//what i did for overloading + operator to get new length out of 2 different lengths

Length operator+ (const Length& lengthA){       

    int newlengthMin = min, newlengthMax = max;

    if (lengthA.min < min)
        newLengthMin = lengthA.min;
    if  (lengthA.max > max)
        newLengthMax = lengthA.max;

    return Length(newLengthMin, newLengthMax);
}

Upvotes: 4

Views: 10929

Answers (4)

Alexander Gessler
Alexander Gessler

Reputation: 46697

For the simple case, use bool operator==(const Length& other) const. Note the const - a comparison operator shouldn't need to modify its operands. Neither should your operator+!

If you want to take advantage of implicit conversions on both sides, declare the comparison operator at global scope:

bool operator==(const Length& a, const Length& b) {...}

Upvotes: 7

Gustav Larsson
Gustav Larsson

Reputation: 8497

Use bool and make sure to add const as well.

bool operator==(const Length& lengthA) const { return ...; }

You can also make it global, with two arguments (one for each object).

Upvotes: 6

retrodrone
retrodrone

Reputation: 5920

Yes, the equality operator is a comparison operation. You'll return a boolean indicating the correct condition. It would be something like this:

bool operator== (const Length& lengthA, const Length& lengthB) const {
    return (lengthA.min == lengthB.min) && (lengthA.max == lengthB.max);
}

Upvotes: 2

salezica
salezica

Reputation: 77129

Take a look at this: http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/

Cheers!

Upvotes: 1

Related Questions