2
votes

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
What do you mean by "might be generated"? It compares if all members are equal, no?user202729
So, does it compare each member?rohitt
Default Comparison Operators - en.cppreference.com/w/cpp/language/default_comparisons "...The default operator<=> performs lexicographical comparison by successively comparing the base (left-to-right depth-first) and then non-static member (in declaration order) subobjects of T to compute <=>, recursively expanding array members (in order of increasing subscript), and stopping early when a not-equal result is found, ..."Richard Critten

1 Answers

3
votes

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.