How to stop overflowing here?

When I run this program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cmath>
using std::sqrt;
class point
{
    public:
        point(int,int);
        int operator - (const point&) const;
    private:
        int x,y;
};

point::point(int a, int b)
{
    x = a;
    y = b;
}

int point::operator- (const point& otherpoint) const
{
    return sqrt( ((x - otherpoint.x) ^ 2) + ((y - otherpoint.y) ^ 2));
}

int main(int argc, const char *argv[])
{
    point a(1,5);
    point b(7,10);
    int distance;
    distance = a - b;
    std::cout << "distance is: " << distance << std::endl;
    return 0;
}

I get this output:

distance is: -2147483648


Clearly, there is some kind of overflowing going on, but I can't figure out how to fix it.Any help is appreciated.
I think it's something to do with that ^ operator.

Try this instead:

 
return sqrt(((x - otherpoint.x) * (x - otherpoint.x)) + ((y - otherpoint.y) * (y - otherpoint.y)));


Also, everything will get truncated, which I'm not sure is what you want. Maybe use doubles or floats.
+ iHutch105.

The ^ operator is bitwise XOR, not exponet. To square something you're better off with x*x.


Also, this is a horrible - operator. I would expect a - operator to return a point like this:

1
2
3
4
5
 
point point::operator- (const point& otherpoint) const
{
  return point( x - otherpoint.x, y - otherpoint.y );
}


What you are doing would be better accomplished with a Distance function or something similar.


Remember the point of operator overloading is not to be cute or to save on typing. It's to make code more intuitive. If your operator does not do what people would immediately expect it to, then it is a poor operator and should be a function instead.
Remember the point of operator overloading is not to be cute or to save on typing. It's to make code more intuitive. If your operator does not do what people would immediately expect it to, then it is a poor operator and should be a function instead.


Completely agree with this. Intuition would suggest that a point - point operation will deduct both the x and y values of the point class. Although operator overloading is a great feature to know, it's equally as important to know when's best to use it.

And thanks for the ^ clarification. I could vaguely remember it being bitwise related, but couldn't remember how exactly.

The ^ operator is bitwise XOR, not exponet


That would explain the weird behaviour :)


Also, this is a horrible - operator.


I guess you are right. I was just trying to see if I could implement a operator overloading, so I thought I might implement something like that.


Remember the point of operator overloading is not to be cute or to save on typing. It's to make code more intuitive.


Noted. Thanks.
Topic archived. No new replies allowed.