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;}
//operators overloading
const Point& operator+(const Point& p)const;
Point& operator=(const Point& p);
friend ostream& operator<<(ostream& os, const Point& p);
};
//overloading << operator
ostream& operator<<(ostream& os, const Point& p)
{
return os<<"("<<p.X<<","<<p.Y<<")";
}
//overloading + operator
const Point& Point::operator+(const Point& p)const
{
cout<<"Operator + called, ";
cout<<"Caller is: "<<*this<<endl;
cout<<"Adding "<<p<<" to "<<*this<<endl;
return Point(X+p.X, Y+p.Y);
}
//overloading = operator
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)
Adding (2,2) to (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)
thanks in advanced!
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?