Search code examples
c++equality

Equality check for objects of classes with explicit constructor only


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?


Solution

  • 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