Skip to main content

ProwessApps

Learn · Practice · Excel

WAP using operator overloading ++ for distance class object(pre and post increment). Also overload unary - for an object.

C++ Code Example — Operator Overloading

ADVERTISEMENT

WAP using operator overloading ++ for distance class object(pre and post increment). Also overload unary - for an object.

Objective

Write a C++ program to overload the increment (++) and unary (-) operators for a Distance class.

Algorithm / Approach

  1. Create a class Distance with meters and centimeters.
  2. Overload Post-increment: Distance operator++(int).
  3. Overload Pre-increment: Distance operator++().
  4. Overload Unary minus: Distance operator-().
  5. In main(), apply these operators directly to a Distance object (e.g., d++, -d).
main.cpp
#include<iostream>
using namespace std;
class Distance {
 int m, cm;
 public:
 Distance(int a, int b) {
  m = a;
  cm = b;
 }
 Distance operator++(int) { 
  m = m+1;
  cm = cm+5;
  return Distance(m,cm);
 }
 Distance operator++() { 
  m = m+3;
  cm = cm+10;
  return Distance(m,cm);
 }
 Distance operator-() {
 m = (-1)*m;
 cm = (-1)*cm;
 return Distance(m,cm);
 }
 void display() {
  cout<< m<<" meter "<< cm<<" cm\n";
 }
};
int main() {
 Distance d(10,20);
 d.display();
 d++;
 d.display();
 ++d;
 d.display();
 d = -d;
 d.display();
 return 0;
}

Expected Output

10 meter 20 cm
11 meter 25 cm
14 meter 35 cm
-14 meter -35 cm

Explanation of the Program

  • Operator Overloading allows you to redefine how standard C++ operators (like +, -, ++, etc.) work when applied to your own custom objects.
  • Notice the dummy int parameter in operator++(int). C++ uses this dummy parameter solely as a signature trick to distinguish the Post-increment operator from the Pre-increment operator.

Complexity

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