Skip to main content

Distance class relational operators

Short answer

Convert each Distance to total inches (feet*12+inches) and overload relational operators to compare these totals, returning bool. For 5'8" (68 in) and 6'2" (74 in), d1 < d2 is true.

Write a program to define a class Distance with necessary data members and functions. Then overload the relational operators to compare the two objects of Distance class.

Class Distance stores a distance in feet and inches. For comparison, both objects are converted into inches (feet * 12 + inches). The six relational operators are overloaded as member functions.

#include <iostream>
using namespace std;

class Distance {
    int feet;
    float inches;
public:
    Distance(int f = 0, float i = 0) { feet = f; inches = i; }

    void getdist() {
        cout << "Enter feet and inches: ";
        cin >> feet >> inches;
    }
    void showdist() { cout << feet << "'-" << inches << "\""; }

    float toInches() const { return feet * 12 + inches; }

    bool operator<(const Distance &d)  const { return toInches() <  d.toInches(); }
    bool operator>(const Distance &d)  const { return toInches() >  d.toInches(); }
    bool operator==(const Distance &d) const { return toInches() == d.toInches(); }
    bool operator!=(const Distance &d) const { return toInches() != d.toInches(); }
    bool operator<=(const Distance &d) const { return toInches() <= d.toInches(); }
    bool operator>=(const Distance &d) const { return toInches() >= d.toInches(); }
};

int main() {
    Distance d1, d2;
    d1.getdist();
    d2.getdist();

    cout << "d1 = "; d1.showdist();
    cout << ", d2 = "; d2.showdist(); cout << endl;

    cout << "d1 <  d2 : " << (d1 <  d2) << endl;
    cout << "d1 >  d2 : " << (d1 >  d2) << endl;
    cout << "d1 == d2 : " << (d1 == d2) << endl;
    cout << "d1 != d2 : " << (d1 != d2) << endl;
    cout << "d1 <= d2 : " << (d1 <= d2) << endl;
    cout << "d1 >= d2 : " << (d1 >= d2) << endl;
    return 0;
}

Sample run:

Enter feet and inches: 5 8
Enter feet and inches: 6 2
d1 = 5'-8", d2 = 6'-2"
d1 <  d2 : 1
d1 >  d2 : 0
d1 == d2 : 0
d1 != d2 : 1
d1 <= d2 : 1
d1 >= d2 : 0

Here 5'8" = 68 in and 6'2" = 74 in, so d1 is smaller. Each operator returns a bool (1 for true, 0 for false), so the result can be used directly in if statements.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →