c++operatorscanonical-form

Canonical form of += operator for classes


I know that it's a good idea to make as much of the interface of a class non-member non-friend as possible, and I've just realised that for my 3D vector class, 'Vector3', I can move the +=, -= and so on operators out of the class, leaving just constructors and the copy assignment operator.

The question is: what should this operator look like? I've seen canonical forms of plenty of other operators and have followed their advice, but I haven't seen canonical forms of these operators. I've given what I think it should be below.

The secondary question is: what are these operators even called? Arithmetic assignment operators?

The (relevant) code before:

class Vector3 {
public:
    Vector3& operator+=(const Vector3& rhs);
    float x, y, z;
};

Vector3& Vector3::operator+=(const Vector3 &rhs) {
    x += rhs.x;
    y += rhs.y;
    z += rhs.z;

    return *this;
}

What I've changed it to so far:

class Vector3 {
public:
    float x, y, z;
};

Vector3& operator+=(Vector3& lhs, const Vector3& rhs) {
    lhs.x += rhs.x;
    lhs.y += rhs.y;
    lhs.z += rhs.z;

    return lhs;
}

Solution

  • What you have looks good to me.

    By the way, when you come to the operator+, it is common to implement that in terms of +=. (create a copy of lhs, and then call lhs += rhs and return the result)

    Don't know if you're already aware of this trick, but since you're concerned about canonical ways to implement these operators, it can't hurt to mention it. :)