In c++ you can create new instances of a class on both the heap and stack. When overloading an operator are you able to instantiate on the stack in a way that makes sense?>
Using your code:
Point Point::operator+ (Point a)
{
Point result(this->x+a.x,this->y+ a.y);
return result;
}
This will work fine.
Basically it creates result localy (on the stack). But the return statement copies the result back to the calling point (just like an int). It uses the Point copy constructor to copy the value back to the call point.
int main()
{
Point a(1,2);
Point b(2,3);
Point c(a + b);
}
Here the operator + creates a local on the stack. This is copied back to the call point (The constructor for c) by the return. Then the copy constructor for c is used to copy the content into c.
But you think that seems a little costly on the copy construction. Technically yes. But the compiler is allowed to optimize away the extra copy constructions (and all modern compilers are very good at it).
Returning to your code.
Point Point::operator+ (Point a)
{
Point *c = new Point(this->x+a.x,this->y+ a.y);
return *c;
}
Don't do this. Here you have allocated dynamically but you are copying the result back to the call point (as described above using the copy constructor). So by the time control returns to the call point you have lost the pointer and can't de-allocate the memory (Thus a memory leak).
The difference between Java and C++ is that when we return pointers we use smart pointers to help the caller identify who is responsible for freeing the memory (look up pointer ownership).