Skip to main content

Relational operators comparing lengths

Short answer

Overload relational operators by converting each length to centimeters (meter*100 + cm) and comparing the totals; operators return bool. For inputs 2 m 50 cm (250 cm) and 1 m 120 cm (220 cm), first length is greater.

Write a program to overload the relational operators to compare the length (in meter and centimeter) of two objects.

Class Length stores meter and centimetre. To compare two lengths, each is converted to centimetres (meter * 100 + cm), and the relational operators <, >, ==, !=, <= and >= are overloaded as member functions returning bool.

#include <iostream>
using namespace std;

class Length {
    int meter;
    float cm;
    float total() { return meter * 100 + cm; }   // length in cm
public:
    void read() {
        cout << "Enter meter and cm: ";
        cin >> meter >> cm;
    }
    void show() { cout << meter << " m " << cm << " cm"; }

    bool operator<(Length l)  { return total() <  l.total(); }
    bool operator>(Length l)  { return total() >  l.total(); }
    bool operator==(Length l) { return total() == l.total(); }
    bool operator!=(Length l) { return total() != l.total(); }
    bool operator<=(Length l) { return total() <= l.total(); }
    bool operator>=(Length l) { return total() >= l.total(); }
};

int main() {
    Length a, b;
    a.read();
    b.read();

    a.show(); cout << " vs "; b.show(); cout << endl;
    if (a == b)      cout << "Both lengths are equal" << endl;
    else if (a > b)  cout << "First length is greater" << endl;
    else             cout << "Second length is greater" << endl;

    cout << "a != b : " << (a != b) << endl;
    cout << "a <= b : " << (a <= b) << endl;
    cout << "a >= b : " << (a >= b) << endl;
    return 0;
}

Sample run:

Enter meter and cm: 2 50
Enter meter and cm: 1 120
2 m 50 cm vs 1 m 120 cm
First length is greater
a != b : 1
a <= b : 0
a >= b : 1

Here 2 m 50 cm = 250 cm and 1 m 120 cm = 220 cm, so the first length is greater.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →