0

I have a vector class

class Vector {
public:
double x, y, z;
Vector operator * (Vector& v) {
    return Vector(x*v.x, y*v.y, z*v.z);
};

a class Ray

class Ray {
    Vector origin, direction;
public:
    Ray();
    Ray(Vector, Vector);
    Vector getRayOrigin() { return origin; }
    Vector getRayDirection() { return direction; }
};

and I have a plane class

class Plane {
public:
Vector normal;
double distance;
double Plane::hit(Ray ray) {
    Vector rayOrigin = ray.getRayOrigin();
    Vector t = normal * rayDirection; // works
    Vector tt = normal * ray.getRayOrigin(); // doesn't work
}

I can't figure out why call normal * ray.getRayOrigin() doesn't work error: Invalid operands to binary expression 'Vector' and 'Vector'

  • 3
    `ray.getRayOrigin()` doesn't return a `Vector&`, it returns a `Vector`, and a temporary one at that. Change the parameter to your operator to `const Vector&` (and as far as that goes, `operator *` is itself worthy of `const` as well). – WhozCraig Jun 29 '15 at 21:48
  • possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – o11c Jun 30 '15 at 02:55

1 Answers1

0

The operation fails because the temporary vector retuned by getRayOrigin() cannot bind to a non-const reference. To fix this, change Vector& v to Vector const & v.

It is considered better style to have operators which don't change the first operand to be non-member functions:

Vector operator * (Vector const & v, Vector const & w)
{
    return Vector(v.x*w.x, v.y*w.y, v.z*v.z);
}

See the operator overloading megathread for more explanation.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365