0

Why can I not check two objects of classes with explicit constructor only for equality? The following code does not compile

struct Foo
{
    explicit Foo(int x) : x_(x) {}
    int x_;
};

int main()
{
    Foo(1) == Foo(1);
}

Do I have to declare operator == explicitly?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134
  • 5
    Because you didn't show the compiler how to compare them. – 101010 Nov 19 '15 at 09:17
  • Oh, sorry. I thought it would have something to do with the ctor being `explicit`, but I just learned, C++ does not create `operator ==` by default: http://stackoverflow.com/questions/217911/why-dont-c-compilers-define-operator-and-operator – Tobias Hermann Nov 19 '15 at 09:19

4 Answers4

2

You need to overload the equality operator==:

struct Foo {
    explicit Foo(int x) : x_(x) {}
    int x_;
};

bool operator==(Foo const &lhs, Foo const& rhs) { return lhs.x_ == rhs.x_; }

LIVE DEMO

101010
  • 41,839
  • 11
  • 94
  • 168
  • 1
    I'd recommend making `operator==` a non-member so it treats its arguments symmetrically. – TartanLlama Nov 19 '15 at 09:21
  • 1
    @101010 I didn't mean the `const`, I meant if any implicit conversions were added later, the lhs would be treated differently from the rhs. With the code written as is, it doesn't make a difference, but I tend to write all relational operators as non-members for consistency. – TartanLlama Nov 19 '15 at 09:23
  • See [this useful guide](http://stackoverflow.com/questions/4421706/operator-overloading) on how best to declare operator overloads. As @TartanLlama points out, `operator==` is best declared as a non-member method, as it treats both operands equally. – Yossarian Nov 19 '15 at 09:24
  • @LogicStuff Nothing wrong I misread the comment of TartanLlama. Thanks for the edit though, it was correct. – 101010 Nov 19 '15 at 09:27
0

How shoud compiler know how it should compare them? Either define operator== or use Foo(1).x_ == Foo(1).x_ if you want to compare those ints.

Maybe you misunderstood what explicit constructor means. It's about asignment operator = and not comparism. Marking your constructor explicits disables following snippet to compile: Foo f = 1.

Zereges
  • 5,139
  • 1
  • 25
  • 49
0

Yes, the compiler does not generate equality for you, so you have to do it yourself. This isn't about explicit constructors either; at no point has C++ ever allowed comparing classes or structs implicitly.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
0

You need an operator == like that:

bool operator==(const Foo& f) { return x_==f.x_; }
Jerome
  • 529
  • 4
  • 14