How to overload compound-assignment in c++?

595 Views Asked by At

point.h

...
Point operator +=(double & left, const Point & right) {
    return Point(left + right.x, left + right.y, left + right.z);
}
// std::ostream is overloaded
...

main.cpp

#include <iostream>
#include "point.h"

int main() {
    double a = 1.0;
    Point b(1.0, 1.0, 1.0);
    a += b;
    std::cout << a << std::endl;
}

Output:

1

I would like to return the sum:

(2, 2, 2)

But the double type is preserved by compiler when compound-assignment.

1

There are 1 best solutions below

0
On

This operator definition

Point operator +=(double & left, const Point & right) {
    return Point(left + right.x, left + right.y, left + right.z);
}

is wrong because it assigns nothing to the left operand and does not return the lvalue of the assigned object.

In general it is better to define such operators as class member functions.

I would define it the following way

class Point
{
    //...
    Point & operator +=( const Point &rhs )
    {
        x += rhs.x;
        y += rhs.y;
        z += rhs.z;

        return *this;
    }
    //...
};

As for your code and particularly this statement

a += b;

then it is not clear whether there is a conversion constructor that converts an object of type double (the type that object a has) to type Point because you did not show the class definition. And as I already pointed out the operator you defined does not change the left operand (a temporary object of type Point that would be created based on the object a). So if even the record above is correct in any case the original object a will not be changed.

For an objects of type double used as the left operand you could define operator + instead of the operator +=.

For example

const Point operator +( double lhs, const Point &rhs )
{
    Point p( rhs.x + lhs, rhs.y + lhs, rhs.z + lhs );

    return p;
}

The details of the implementation for your class can be different because I do not see the class definition. Nevertheless this definition demonstrates the idea.

In this case you could write

double a = 1.0;
Point b( 1.0, 1.0, 1.0 );

std::cout << a + b << std::endl;

and get the expected result

(2, 2, 2)