operator overloading explanation needed

Please have a look at the code and let me know why doe we use the following:

temp.longitude=op2.longitude+longitude; //how does this line work?
temp.latitude=op2.latitude+latitude

The part of the code is here to add two objects:

class loc{
int longitude,latitude;
public:
loc() {}
loc(int lg,int lt){
longitude=lg;
latitude=lt;
}
loc operator+(loc op2);
};

loc loc::operator+(loc op2){
loc temp;
temp.longitude=op2.longitude+longitude;
temp.latitude=op2.latitude+latitude;
return temp;
}
First of all, you should place your code within code tags. You can edit your post, highlight your code, and click on the Format button that looks like "<>". For some reason this does not work when creating a thread, but you can always edit your post.

Now, your question.

The operator+() function takes a loc object, and returns a new loc object which is the sum of the 2 loc objects. For instance, if you do the following:

1
2
3
loc a(5, 10);
loc b(3, 9);
loc c = a + b;


you create 3 loc objects. The loc "c" is created by adding a and b together. Adding the loc objects means adding the piece parts of the loc objects.

The operator+() function is called on object "a" because it is on the lefthand side of the addition statement. b.longitude is added to a.longitude and stored in temp.longitude. Likewise with latitude. The value temp is returned and assigned to c.

Do you realize that there are two latitudes available in that function? The latitude of the current object and the latitude of the object passed into the function.

1
2
3
4
5
6
7
8
9
loc loc::operator+(loc op2)
{
    loc temp;
    temp.longitude = this->longitude + op2.longitude;
    temp.longitude = this->latitude += opt2.latitude;

    return temp;
}
Topic archived. No new replies allowed.