2

Possible Duplicate:
Operator Overloading in C++ as int + obj
Operator overloading

I have a Point object with this operator:

Point operator +(float other) const {
  return Point(x + other, y + other, z + other);
}

I can perform addition like so:

point + 10

But I can't perform it in reverse order:

10 + point

Is there another operator I need to overload in order to provide this functionality?

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496

4 Answers4

3

You normally want to overload the global operator:

Point operator+(Point const &a, float b);
Point operator+(float a, Point const &b);

Instead of two overloads, you may want to use only one overload:

Point operator+(Point const &a, Point const &b);

and then have a ctor to create a Point from a float:

class Point { 
    public:
        Point(float);
};

In this case, adding a float to a Point will use the ctor to convert the float to a Point, then use your overloaded operator+ to add those two Points together.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 1
    Indeed. But many (e.g. Meyers) would argue that implicit conversion constructors can lead to issues... – Oliver Charlesworth Oct 04 '11 at 17:53
  • @OliCharlesworth: they certainly *can* lead to some issues, but when you look carefully, they arise most often when you convert from class to basic type. From basic type to class *tends* to be a lot safer (though it certainly *can* still raise issues). – Jerry Coffin Oct 04 '11 at 18:29
  • 1
    Especially in this case: `point + 10` is already combining the mathematical notions of vector and scalar values, by allowing the user to write `10` in place of `point_offset(10,10,10)` (note that a point and a vector value are also slightly different - vectors can be used to denote points relative to an origin, but not all vectors *are* points and it's mathematically meaningless to "add two points together"). If you're going to combine those concepts anyway, then to me it makes sense to allow that implicit conversion. If you're not going to combine them, don't allow `Point + float` either. – Steve Jessop Oct 04 '11 at 18:43
2

As a free function:

Point operator+(float other, const Point &pt) {
    return pt+other;
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

Given an existing Point& Point::operator+=(float other), add these two free functions:

Point operator+(Point pt, float other) {
  return pt += other;
}
Point operator+(float other, Point pt) {
  return pt += other;
}
Blender
  • 289,723
  • 53
  • 439
  • 496
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

Outside of the class:

inline Point operator+(const float& other, const Point& pnt) { return Point(...); };
KQ.
  • 922
  • 4
  • 8