user11438875
user11438875

Reputation:

why is this 'a' = 2, instead of 7?

I am overloading operator '/'. when I divide object 'a' with object 'b' (under main), object 'a' is changed to 2, instead of equaling 7, as it was previously to the division. Is this an error? If not, why is the 'a'=2 and not 7?

#include <iostream> 
using namespace std;
class OO{
  int x;
  int y;
  public:
         OO(){x=y=0;}
         OO(int i, int j){x=i;y=j;}
         OO operator+(OO ob){
                         OO temp;
                         temp.x=x+ob.x;
                         return temp;
                         }
         OO operator=(OO ob){
                        x=ob.x;
                        return *this;
                        } 
         OO operator/(OO ob){
                        x=x/ob.x;
                        return *this;
                        }
         OO operator++(){
                         OO temp;
                         temp.x=++x;
                         return temp;

                         }                                            
         void show(){

              cout<<x<<endl;

              }                             

  };


int main() {
OO a(6,2);
OO b(3,2);
b.show();
a.show();
OO c = a + a;
c.show();
++a;
a.show();
c = a / b;
a.show();//why is this 'a' = 2, instead of 7?
c.show();
c=b=a;
c.show();
}

Upvotes: 0

Views: 76

Answers (2)

John M.
John M.

Reputation: 265

When you call c = a / b, your compiler understands a.operator/(b). That means your implementation will actually change the value of a and the result will be the division of a / b, which in this case is 7/3. However 7/3 is a division between integers, thus the result will be truncated and that will net you the number 2.

Upvotes: 0

user10957435
user10957435

Reputation:

You're modifying a inside the operator on this line:

x=x/ob.x;

That modifies x. What you want is what you did for operator+(). That is, create a temp object and return that instead:

OO operator/(OO ob){
    OO temp;
    temp.x=x/ob.x;
    return temp;
}

Upvotes: 2

Related Questions