Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default equality operator C++20

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;
}
like image 817
rohitt Avatar asked Aug 26 '26 20:08

rohitt


1 Answers

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.

like image 190
Nicol Bolas Avatar answered Aug 29 '26 09:08

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!