Reputation: 519
I've been practicing creating copy constructors and overloading operators, so I was wondering if someone could check if my implementation is correct. This is just an arbitrary practice example.
class Rectangle
{
private:
int length;
int width;
public:
Rectangle(int len = 0, int w = 0)
{
length = len;
width = w;
}
Rectangle(const Rectangle &);
Rectangle operator + (const Rectangle &);
Rectangle operator = (const Rectangle &);
};
Rectangle::Rectangle(const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "copy constructor" << endl;
}
Rectangle Rectangle::operator + (const Rectangle &right)
{
Rectangle temp;
temp.length = length + right.length + 1;
temp.width = width + right.width + 1;
cout << "+ operator" << endl;
return temp;
}
Rectangle Rectangle::operator = (const Rectangle &right)
{
Rectangle temp;
temp.length = right.length + 2;
temp.width = right.width + 2;
cout << "= operator" << endl;
return temp;
}
Upvotes: 1
Views: 54
Reputation: 49986
Your copy assignment operator should return a reference to itself, and also do the assignment:
Rectangle& Rectangle::operator= (const Rectangle &right)
{
length = right.length;
width = right.width;
cout << "= operator" << endl;
return *this;
}
as for:
Rectangle(int len = 0, int w = 0)
I recomend making it explicit, to prevent implicit conversions from integer.
Upvotes: 2