4

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);
}
2
  • There can only be one result. Note the operator == is a comparison (or should be for consistency). So it should return true/false depending on the equality comparison of two lengths. Commented Apr 4, 2011 at 21:07
  • oh aright so in a sense it returns the answer automatically for u based on its comparison right? Commented Apr 4, 2011 at 21:12

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

2

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);
}

Comments

1

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

Cheers!

2 Comments

Uhm... it's the logical and operator. You shouldn't be tackling operator overloading without that kind of previous knowledge. Try taking the tutorial from the beginning!
too big a bite out of a delicious pie u cant resist...haha thnx anyway

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.