1. ## trouble with overloaded operator

Hey I am having some trouble getting operator/ to overload to a midpoint formula for a Point class. And yes, I have to make operator/ find the midpoint it was part of the assignment.

Anyway I came up with this:

Code:
```// Overloaded operator/ to return the midpoint
// between two Point objects, however it does not
// work and only returns garbage.

Point & Point::operator/(const Point & p) const
{
return Point(((x + p.x) / 2.0), ((y + p.y) / 2.0));
}```
here is the header file if you want to look at that too:

Code:
```#ifndef POINT_CLASS_HEADER_INCLUDED

#include <iostream>

// A 2D point class
class Point
{
double x, // x coordinate of point
y; // y coordinate of point

public:

Point(void);
Point(double new_x, double new_y);
Point(const Point & p);

void Output(void);   // output this point
void Input(void);    // input this point
double distance(Point other);   // distance between this point and other

double get_x(void) { return x; }
double get_y(void) { return y; }

void set_x(double new_x);
void set_y(double new_y);

Point flip_x(void);
Point flip_y(void);

Point shift_x(double move_by);
Point shift_y(double move_by);

Point & operator=(const Point & p);

Point & operator/(const Point & p) const;
double operator-(const Point & p) const;

bool operator==(const Point & p) const;
bool operator!=(const Point & p) const;

double operator[](const char axis) const;
double & operator[](const char axis);

friend std::istream & operator>>(std::istream & in, Point & p);
friend std::ostream & operator<<(std::ostream & out, const Point & p);

};

#endif```
Anyway I was wondering if that is an invalid operator overload and if it is how can a hack it together to get it to work? Any ideas?

2. ## Re: trouble with overloaded operator

Originally posted by kkurz
Hey I am having some trouble getting operator/ to overload to a midpoint formula for a Point class. And yes, I have to make operator/ find the midpoint it was part of the assignment.

Anyway I came up with this:
Code:
```// Overloaded operator/ to return the midpoint
// between two Point objects, however it does not
// work and only returns garbage.

Point & Point::operator/(const Point & p) const
{
return Point(((x + p.x) / 2.0), ((y + p.y) / 2.0));
}```
You are returning a reference to a new Point object created on the stack inside the operator/ function. When the function ends, all objects created inside it are destroyed, including the one that you returned a reference to. The reference you returned is then pointing at diddly poo. In this case I'd say return a Point and not a Point reference.

3. ## Thanks so much

Thanks, I really appreciate it that fixed everything right up.

I really have to work on being able to go through my code and actually analyzing it, instead of reading it and saying, "sure that looks good to me."

Thanks again.

Kevin