rishabh jindal
rishabh jindal

Reputation: 31

Operator overloading:how in unary operator overloading function return is working in this code?

#include <iostream>
using namespace std;

class Distance
{
   private:
   int feet;             // 0 to infinite
   int inches;           // 0 to 12
   public:
   // required constructors
   Distance(){
     feet = 0;
     inches = 0;
   }
   Distance(int f, int i){
     feet = f;
     inches = i;
   }
   // method to display distance
   void displayDistance()
   {
      cout << "F: " << feet << " I:" << inches <<endl;
   }
   // overloaded minus (-) operator
   Distance operator- ()  
   {
     feet = -feet;
     inches = -inches;
     return Distance(feet, inches);
   }
   };
   int main()
   {
      Distance D1(11, 10), D2(-5, 11);

      -D1;                     // apply negation
      D1.displayDistance();    // display D1

      -D2;                     // apply negation
      D2.displayDistance();    // display D2

      return 0;
    }

if a instance of Distance is to be returned in operator-() function shouldn't it be returned like new Distance(feet,inches). how this line of code is working here? //return Distance(feet,inches);

Upvotes: 0

Views: 327

Answers (3)

Ravi
Ravi

Reputation: 90

...

// overloaded minus (-) operator
    Distance &operator- ()
    {
        feet = -feet;
        inches = -inches;
        return (*this);
    }
};


int main(int argc, const char * argv[]) {

    Distance D1(11, 10), D2(-5, 11);

    D1.displayDistance();
    -D1;
    D1.displayDistance();    // apply negation and display D1

    D2.displayDistance();
    (-D2).displayDistance();    // apply negation and display D2
    (-D2).displayDistance();    // apply negation again and display D2

    return 0;
}

Upvotes: 0

Ravi
Ravi

Reputation: 90

It appears to work due to the following reasons:

  1. Internally the variables feet and inches being negated i.e., mutable values.
  2. Then printing the value of D1 or D2 as the case may be.
  3. Ignoring the objects being returned from the operator, which is wrong.

The unary operator overloading should have been:

Distance & operator- ()
{
    feet = -feet;
    inches = -inches;
    return *this;
}

Upvotes: -1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

if a instance of Distance is to be returned in operator-() function shouldn't it be returned like new Distance(feet,inches)

No, new isn't necessary here. Just return a copy.

Actually the implementation of the negation operator should look like

Distance operator- () const
{
    return Distance(-feet, -inches);
}

without touching the current instances member variables (const guarantees that).

Upvotes: 3

Related Questions