Hi,
I wrote the this following simple, straightforward code (for learning purpuses only), and played with it a little bit.
there's something I wanted to ask though.
first here's the code:

Code:
```#include<iostream>
#include<string>
using namespace std;

//class Point
class Point
{
private:
int X;
int Y;
public:
//constructors
Point(int x=0, int y=0):X(x), Y(y){cout<<"Ctor called to construct "<<*this<<endl;}
Point(const Point& point);
//destructor
~Point(){cout<<"Destructor called to destruct "<<*this<<endl;}
const Point& operator+(const Point& p)const;
Point& operator=(const Point& p);
friend ostream& operator<<(ostream& os, const Point& p);
};

ostream& operator<<(ostream& os, const Point& p)
{
return os<<"("<<p.X<<","<<p.Y<<")";
}

const Point& Point::operator+(const Point& p)const
{
cout<<"Operator + called, ";
cout<<"Caller is: "<<*this<<endl;
return Point(X+p.X, Y+p.Y);
}

Point& Point::operator=(const Point& p)
{
cout<<"Operator = called, ";
cout<<"Assigning "<<p<<" to "<<*this<<endl;

X=p.X;
Y=p.Y;
return *this;
}

//the copy constructor
Point::Point(const Point& point)
{
cout<<"CCtor called: ";
cout<<"Copying the point "<<point<<endl;
X=point.X;
Y=point.Y;
}

//main
int main()
{
Point p0, p1(1,1), p2(2,2);
p0=p1+p2;
}```
Now, I know, that the + operator should return a Point object by value, meaning its prototype should be:
Code:
`Point Point::operator+(const Point& p)const`
but I wanted to see what output I'll get if I change it.

so this is the output I get for the above main() function, and the question is in it.

Code:
```Ctor called to construct (0,0)
Ctor called to construct (1,1)
Ctor called to construct (2,2)
Operator + called, Caller is: (1,1)
Ctor called to construct (3,3)
Destructor called to destruct (3,3) //temp object was destroyed here
Operator = called, Assigning (3,3) to (0,0) //so how can it be assigned to (0,0) here?
Destructor called to destruct (2,2)
Destructor called to destruct (1,1)
Destructor called to destruct (3,3)```

P.S, any additional useful tips are very welcome.
like, for example, when is it a good idea to return by value and when by reference?
and what about concatenation? where does it need special consideration? 2. You're returning a const reference to a temporary. That's not allowed, because as you can see, the temporary is destroyed before the function returns. However, in this small program, nothing bad happens, because even though the temporary variable is destroyed and is no longer tracked, nothing has a chance to overwrite it, so the data is still there.

So what you have is undefined behavior. It might work on your compiler, maybe even most compilers, but it is not legal C++.

In general, for return values, it's fast and convenient to return by value, unless you're just returning a reference that's a function argument or to a global variable. Popular pages Recent additions 