I want to add overloaded operators to my Point class that allow me to do operations like:
1 2 3 4
Point* p1 = new Point(5, 10);
Point* p2 = new Point(1, 5);
Point* p3 = 2 * p1 + p2; // Should be: [11, 25]
Now, how would I manage the memory allocation of these variables?
2 * p1
Should create a new point, [10, 20]. Should I allocate its memory (by initializing a new Point in the operator function)? Because if I do, when will it ever be released from memory?
Or is there another obvious way I'm missing? The whole reason I want these overloaded operators is because I want it to be easy to work with these Points.
You don't have to worry about allocation. Just create a Point in your operator body, put the result inside and return it. The compiler will allocate a copy of that Point that can be usedd in the second operator, whose return value will be used in the assignment operator. No need to worry about dynamic allocation and liberation
Almost there. Now that you stopped using new, you also need to stop using pointers inappropriately. In your operator*, you're returning a pointer to a local variable which is destroyed as soon as the function returns.
1 2 3 4
Point operator*(double a,const Point& p)
And yes, you don't have to worry about memory as long as you don't use new.