-1

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.

Danilo
  • 175
  • 1
  • 11
  • 4
    `a` is a double. There is no way `cout << a << endl;` will ever return `(2, 2, 2)`. Also, `+=` is supposed to modify the LHS operand, not create a new object with a different type. – juanchopanza Aug 15 '15 at 09:05
  • what you really want to do is swap operands in your += operator, modify an existing point in it instead of creating a new one, and in your main.cpp use b += a. – Pavel Lint Aug 15 '15 at 09:08
  • @Danilo Show the class definition. – Vlad from Moscow Aug 15 '15 at 09:09
  • See http://stackoverflow.com/questions/4421706/operator-overloading – juanchopanza Aug 15 '15 at 09:09
  • You are mixed up. Variables can't change their type in C++; once `a` is a double it is always a double. Perhaps you meant something like `Point c = a + b;` – M.M Aug 15 '15 at 09:39

1 Answers1

2

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)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335