Myone
Myone

Reputation: 1131

operator== order in C++

Is there ever any difference when it comes to order with the operator==?

I came across an old exam where it says:

observe that *it1 == *it2 is not the same as *it2 == *it1

it1 in this case is an iterator of some type IT1 and it2 is an iterator of some type IT2. IT1 it1 and IT2 it2 are taken as parameters to a function, where IT1 could be the same as IT2. Example code:

template <typename IT1, typename IT2>
bool f(IT1 it1, IT2 it2) {
    return *it1 == *it2;
}

Any thoughts? In my head, order should not affect the outcome of operator==, so I'm confused.

Upvotes: 3

Views: 85

Answers (3)

Matt
Matt

Reputation: 15081

Well, actually operator overloading could produce unexpected results. Consider the following:

#include <iostream>

class Bar;

class Foo {
public:
    Foo() {}
    int operator==(const Bar& bar) { std::cout << "foo == bar\n"; return 0; }
};

class Bar {
public:
    Bar() {}
    int operator==(const Foo& foo) { std::cout << "bar == foo\n"; return 0; }
};

int main()
{
    Foo foo;
    Bar bar;

    foo == bar; // prints "foo == bar"
    bar == foo; // prints "bar == foo"

    return 0;
}

Here actually two different operator== get called.

Upvotes: 2

Jonathan Wood
Jonathan Wood

Reputation: 67195

The == operator tests if the values on both sides of the operator are equal.

How could it possibly matter which value goes on the left and right sides of the operator? That has no bearing on whether or not they are equal.

Of course, you could overload the operator to have some non-standard behavior, in which case it could matter. But that would be a bad approach, and would not make clear which value should go on the left and which value should go on the right side of the operator.

Upvotes: 1

Tom Tromey
Tom Tromey

Reputation: 22519

Yes, there can be a difference, because a given implementation of operator== can be asymmetric. Generally speaking this is not a very good way to code, but it can happen. == is symmetric for primitive types like int, but for user-defined classes anything can happen.

Upvotes: 4

Related Questions