Reputation: 31
#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
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
Reputation: 90
It appears to work due to the following reasons:
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