0

I am trying to overload the =, + += operators and the first two worked fine but the operator+=() function is producing an error.
Here is the code for the three:

Overloading '=' operator

inline vec3& operator = (vec3& ob) { 
    mX = ob.getX();
    mY = ob.getY();
    mZ = ob.getZ();

    return *this;
}

Overloading '+' operator

vec3 vec3::operator + (const vec3& ob) {
    vec3 vec(mX + ob.getX(), mY + ob.getY(), mZ + ob.getZ());
    return vec;
}

Overloading '+=' operator

vec3& vec3::operator += (const vec3& obj) {
    *this = *this + obj;
    return *this;
}

Error

binary '=': no operator found which takes a right-hand operand of type 'vec3'

The Hawk
  • 5
  • 1
  • 8

1 Answers1

0

The assignment operator should be const:

vec3& operator= (const vec3& ob)
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Great! that helped. But why didn't it work in the previous case ? – The Hawk Dec 31 '18 at 13:36
  • Without the `const`, the RHS has to be a lvalue. – Eljay Dec 31 '18 at 13:52
  • Yea but that is what I am asking. How does the `const` change it to rvalue ? @Eljay – The Hawk Dec 31 '18 at 14:42
  • `const&` can be used on temporary objects to extend their lifetime. There are plenty of questions on SO about this effect. – Matthieu Brucher Dec 31 '18 at 14:43
  • 1
    If you have a `vec3 const&` parameter, it can take an rvalue or lvalue argument. If you have a `vec3&` parameter, it can only take a lvalue argument. Adding the `const` does not change the argument to an rvalue. – Eljay Dec 31 '18 at 14:46
  • I think you misunderstood me. What I meant was that I just read an SO QA where it said that `vec3& operator= (const vec3& ob)` can be used on rvalue objects like `(a = b+c)` whereas `vec3& operator= (vec3& ob)` wont work. So my question is what is the `const` keyword doing internally, which triggers this behavior ? @MatthieuBrucher – The Hawk Dec 31 '18 at 15:05
  • As @Eljay said, it doesn't do anything, it can capture both rvalues and lvalues (because it's const). – Matthieu Brucher Dec 31 '18 at 15:09
  • why doesn't the non-const (`vec& operator = (vec3& ob)`) capture the rvalues ? – The Hawk Dec 31 '18 at 15:12
  • Because it's not `const`. Say you have `foo(int& i)`, you don't expect it to capture `foo(0)`. But `foo(const int& i)` will. As I've said, plenty of questions with great answers about this. – Matthieu Brucher Dec 31 '18 at 15:13
  • Finally! An answer that simple and clear cleared away all the blockage in my head. Huge thumbs up dude ;) – The Hawk Dec 31 '18 at 15:19