Answer to Question #179413 in C++ for Waleed Abid

Question #179413

Write a class for Distance which have two parts inches and feet as floating data members. Write an overloaded function for (+) binary operator to add the inches and feet of two distance objects. Main function is also necessary to show the working of the Class.




1
Expert's answer
2021-04-10T01:30:39-0400
#include <iostream>
using namespace std;
 
class Distance {
    int feet, inches;
         
    public:
    // default constructor
   Distance() {
      feet = 0;
      inches = 0;
    }  
   // parameterized constructor
    Distance(int f, int i){
      feet = f;
      inches = i;
}
        void readDistance();  // to read distance
        void displpay();   // to display distance
        //add two Distance using + operator overloading
    Distance operator+(Distance &other)   {
            Distance otherDistance;      
            otherDistance.inches = inches + other.inches;
            otherDistance.feet   = feet   + other.feet + (otherDistance.inches/12);
            otherDistance.inches = otherDistance.inches%12;
            return otherDistance;
        }
};
 void Distance::readDistance()  {
       cout << "Enter feet: ";
       cin >> feet;
       cout << "Enter inches: ";
       cin >> inches;
    }
void Distance:: displpay()  {
        cout << "Feet: " << feet << "  " << "Inches: " << inches << endl;
    }

int main() {
    Distance Dist_1, Dist_2, Dist_3;
     
    cout << "Enter first  Distance:" << endl;
    Dist_1.readDistance();
    cout << endl;
     
    cout << "Enter second Distance:" << endl;
    Dist_2.readDistance();
    cout << endl;
     
    //sum:
    Dist_3 = Dist_1 + Dist_2;
     
    cout << "Distance_1 + Distance_2: "<<endl ;
    Dist_3.displpay();
 
    cout << endl;
    return 0;
}







Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS