Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

C++ program to overload binary operators

YASH PAL, 31 July 202422 August 2024

In this post, we will write a C++ program to overload binary operators.

C++ program to overload binary operators

C++ program to overload binary operators.

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

class weight
{
    private:
        int kg,g,mg;

    public:
        weight()
        {
            kg = 0;
            g = 0;
            mg = 0;
        }
        weight(int a, int b, int c)
        {
            kg = a;
            g = b;
            mg = c;
        }
        getdata()
        {
            std::cout<<"Enter the kg = ";
            std::cin>>kg;
            std::cout<<"Enter the g = ";
            std::cin>>g;
            std::cout<<"Enter the mg = ";
            std::cin>>mg;
        }
        showdata()
        {
            std::cout<<"The weight is = "<<kg<<" "<<g<<" "<<mg<<std::endl;
        }
        weight operator + (weight w5)
        {
            int i = kg+w5.kg;
            int j = g+w5.g;
            int k = mg+w5.mg;

            return weight(i,j,k);
        }
        weight operator - (weight w5)
        {
            int i = kg-w5.kg;
            int j = g-w5.g;
            int k = mg-w5.mg;
            return weight(i,j,k);
        }
        weight operator * (weight w5)
        {
            double i = 5*w5.kg;
            double j = 5*w5.g;
            double k = 5*w5.mg;
            return weight(i,j,k);
        }
};

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

    weight w1,w3,w4,w6;
    w1.getdata();

    weight w2(15,100,150);
    w3 = w1+w2;
    w4 = w1-w2;
    w6 = w2*w1;
    w3.showdata();
    w4.showdata();
    w6.showdata();

    getch();
    return 0;
}

Output

Enter the Kg = 100
Enter the g = 900
Enter the mg = 500
Enter the weight is = 115   1000    650
The weight is = 85  800     350
The weight is = 500     4500    2500
coding problems cpp

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes