Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to overload Binary + in following formats.
d1 + d2.
d1 + 4
5 + d1, where d1 and d2 are the object of Distance class

C++ Code Example — Operator Overloading

ADVERTISEMENT

WAP to overload Binary + in following formats.
d1 + d2.
d1 + 4
5 + d1, where d1 and d2 are the object of Distance class

Objective

Write a C++ program to overload the binary (+) operator to handle mixed data types (Object + Object, Object + Int, Int + Object).

Algorithm / Approach

  1. Create a class Distance.
  2. Overload for Object + Object: Distance operator+(Distance d2) (Member function).
  3. Overload for Object + Int: Distance operator+(int a) (Member function).
  4. Overload for Int + Object: friend Distance operator+(int a, Distance d) (Friend function).
  5. Test all three equations in main().
main.cpp
#include<iostream>
using namespace std;
class Distance {
 int m, cm;
 public:
 Distance(int a, int b) {
  m = a;
  cm = b;
 }
 void display() {
  cout<< m<<" m "<< cm<<" cm"<< endl;
 }
 Distance operator+(Distance d2) {
  int x, y;
  x = m+d2.m;
  y = cm+d2.cm;
  return Distance(x,y);
 }
 Distance operator+(int a) {
  int x, y;
  x = m;
  y = cm+a;
  return Distance(x,y);
 }
 friend Distance operator+(int a,Distance d);	
};
Distance operator+(int a, Distance d2) {
 int x, y;
 x = a+d2.m;
 y = d2.cm;
 return Distance(x,y);
}
int main() {
 Distance d(10,20);
 Distance d2(50,60);
 Distance d3 = d+d2;
 d3.display();
 Distance d4 = d+2;
 d4.display();
 Distance d5 = 2+d;
 d5.display();
 return 0;	
}

Expected Output

60 m 80 cm
10 m 22 cm
12 m 20 cm

Explanation of the Program

  • When doing d1 + 4, the compiler calls the member function of d1 and passes 4 as the argument.
  • However, when doing 5 + d1, the integer 5 is on the left. Integers are primitive types; they don't have member functions! Therefore, this specific variation MUST be handled by a global friend function that accepts both the integer and the object as arguments.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT