In this post, we will write a C++ program for binary operator overloading.

C++ program for binary operator overloading


C++ program for binary operator overloading.

#include<iostream>
#include<conio.h>

class distance
{
    private:
        int feet;
        float inches;

    public:
        distance()
        {
            feet = 0;
            inches = 0.0;
        }
        distance(int ft, float in)
        {
            feet = ft;
            inches = in;
        }
        void input()
        {
            std::cout<<"Enter the feet = ";
            std::cin>>feet;
            std::cout<<"Enter the inches = ";
            std::cin>>inches;
        }
        void dis()
        {
            std::cout<<feet<<"\t"<<inches<<std::endl;
        }
        distance operator +(distance);
};

int main()
{
    system("cls");

    distance dis1, dis3;
    dis1.input();
    distance dis2(11,6.5);
    dis3 = dis1+dis2;
    std::cout<<"Distances"<<std::endl;
    dis1.dis();
    dis2.dis();
    dis3.dis();

    getch();
    return 0;
}

distance distance :: operator + (distance d2)
{
    distance temp;
    temp.feet = feet+d2.feet;
    temp.inches = inches+d2.inches;
    return(temp);
}



Output

Ente the feet = 2
Enter the inches = 5.9
Distances
2       5.9
11      6.5

13      12.4