Home » C++ solved programs » C++ operator overloading programs

C++ program to add two distances using binary plus (+) operator overloading

This program will demonstrate example of Binary Plus Operator Overloading, in this program we will take two distances and adding them.

Adding two distances using binary plus (+) operator overloading program in c++.



/*C++ program to add two distances using binary plus (+) operator overloading.*/
 
#include<iostream>
using namespace std;
 
class Distance
{
    private:
        int feet,inches;
         
    public:
        //function to read distance
        void readDistance(void)
        {
            cout << "Enter feet: ";
            cin >>feet;
            cout << "Enter inches: ";
            cin >>inches;
        }
        //function to display distance
        void dispDistance(void)
        {
            cout << "Feet:" << feet << "\t" << "Inches:" << inches << endl;
        }
        //add two Distance using + operator overloading
        Distance operator+(Distance &dist1)
        {
            Distance tempD;     //to add two distances
            tempD.inches= inches + dist1.inches;
            tempD.feet  = feet   + dist1.feet + (tempD.inches/12);
            tempD.inches=tempD.inches%12;
            return tempD;
        }
};
int main()
{
    Distance D1,D2,D3;
     
    cout << "Enter first  distance:" << endl;
    D1.readDistance();
    cout << endl;
     
    cout << "Enter second distance:" << endl;
    D2.readDistance();
    cout << endl;
     
    //add two distances
    D3=D1+D2;
     
    cout << "Total Distance:" << endl;
    D3.dispDistance();
 
    cout << endl;
    return 0;
}

Output

    Enter first  distance:
    Enter feet: 22
    Enter inches: 10

    Enter second distance:
    Enter feet: 23
    Enter inches: 11

    Total Distance:
    Feet:46	Inches:9




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.