Adamska_01
Adamska_01

Reputation: 37

Issues with Operator += in C++

I just went back from operators' declaration in C# and I have learned that, in general, if I have a + and a = operators, I implicitly get a += operator (and the same goes for -, *, /). So I opened one of my old C++ projects and checked if I had the same results. I tried doing this in a "Vector2D" class after deleting the += operator:

Vector2D a(2, 3);
Vector2D b(50, 14);

a += b;

The compiler says "no operator "+=" matches these operands". Why? Here is the code of + and = :

Vector2D Vector2D::operator+(const Vector2D& v) const
{
    return Vector2D(x + v.x, y + v.y);
}

Vector2D& Vector2D::operator=(const Vector2D& v)
{
    x = v.x;
    y = v.y;
    return *this;
}

EDIT

This works btw:

a = a + b;

Upvotes: 0

Views: 159

Answers (1)

Loki Astari
Loki Astari

Reputation: 264381

Normally you define the operator+ in terms of the operator+=.

// Define the += operator to modify the current object.
Vector2D& Vector2D::operator+=(const Vector2D& v)
{
    x += v.x;
    y += v.y;
    return *this;
}
// Define the + operator as copying the current object
// using the standard copy construtor. Then use += to 
// implement the actual addition.
Vector2D Vector2D::operator+(const Vector2D& v) const
{
    Vector2D result(*this);  // Copy.
    return result += v;      // Return the result of +=
                             // Modern compilers will optimize this
                             // correctly.
}

Upvotes: 3

Related Questions