1

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;
}
Eric Larson
  • 509
  • 3
  • 14

1 Answers1

2

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.

marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Could you explain the difference between returning a reference like you suggested and returning an object? Wouldn't both work? – Eric Larson May 02 '16 at 18:17
  • @Matimio this is because synthesized copy assignment operator returns non const reference. This also is faster than making a temporary plus any additional copies. – marcinj May 02 '16 at 18:29
  • Maybe it would be better to write to constructors `Rectangle(int len, int w)` and `Rectangle()`, so that you cannot accidentally create a `Rectangle` with `len` and without `w`. – rodrigo May 02 '16 at 18:31
  • @Matimio Have a look at this question: http://stackoverflow.com/questions/3105798/why-must-the-copy-assignment-operator-return-a-reference-const-reference – Fabio says Reinstate Monica May 02 '16 at 18:50