Overloading Binary and Assignment Operators in Vector Class

Hi,

I am making a vector class and am having some problems creating the overloaded arithmetic operators and assignment operators.

Here is an example of my "+=" code as it stands the errors are similar/the same for the other operators except "=" operator which works fine:

1
2
3
4
5
6
Vector3& Vector3::operator+=(const Vector3 &rhs)
{
    Vector3 tmp = *this;
    Set(tmp.getX() + rhs.getX(), tmp.getY() + rhs.getY(), tmp.getZ() + rhs.getZ());
    return *this;
}


I have tried a lot of different approaches ad always get the error:

error: passing 'const Vector3' as 'this' argument of 'double Vector3::getX()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getY()' discards qualifiers
error: passing 'const Vector3' as 'this' argument of 'double Vector3::getZ()' discards qualifiers


Anyone know why this is? I am guessing it is something pretty simple that I am missing.

Thanks.
The error message looks like getX/Y/Z are not declared const, so you are not allowed to call them on a const instance, in this case rhs.
Last edited on
rhs is a const object. getX, getY and getZ don't operate on const objects (as they should.)

Solution: change the definition of Vector3, so that getX, getY and getZ do operate on const objects.

1
2
3
4
5
 class Vector3 {
    // ...
    int getX() const ;
    // ...
};
Last edited on
I assumed that that couldn't be the problem because I was sure I had declared the getX etc to be const but I look there and you're right I had forgotten to do it. Thanks for the quick response.
Is there any particular reason you are forwarding access to X/Y/Z with getters and setters? It seems pointless in this case.
Because I plan to use operators ([]) to access them later and just made these temporarily.
Topic archived. No new replies allowed.