default equality operator C++20

959 Views Asked by At

In C++20, if we use the default <=>, then all the other comparison operators are also added.
Here in the code the class has two integers so to compare there would be user-defined comparison required. But since the equality operator will be generated automatically, I need to know how it will compare the objects. What happens if there is a composite type.

#include<compare>
#include<iostream>
using namespace std;
class Point {
    int x;
    int y;
public:
    Point(int x, int y):x(x),y(y){}
    friend strong_ordering operator<=>(const Point&, const Point&) = default;
};

int main()
{
    Point p(2,3), q(2,3);
    
    if(p==q) cout << "same" << endl;
    else cout << "different" << endl;

    return 0;
}
1

There are 1 best solutions below

2
On

All defaulted comparison operators of any kind work the same way. They compare all subobjects (base classes and members), in declaration order, one after the other, until the comparison criteria is determined.

So for equality testing, it tests Point::x, then Point::y. But it will stop at x if x were unequal.