Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 624
andrew Avatar asked Dec 04 '22 22:12

andrew


2 Answers

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) {...}

like image 155
Alexander Gessler Avatar answered Dec 09 '22 14:12

Alexander Gessler


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).

like image 31
Gustav Larsson Avatar answered Dec 09 '22 14:12

Gustav Larsson