Sachin Godishela
Sachin Godishela

Reputation: 3

Using member functions in operator overloading definition (error with const)

I am getting error in the operator overloading definition. The error goes away if I remove the consts in the parameters. Is there any way I can get it working without removing the consts in the parameters? Also what is happening behind them?

class Vector3D{
public:
    float x, y, z;
    float dot(Vector3D& v) {
        return x * v.x + y * v.y + z * v.z;
    }
}; 
inline float operator *(const Vector3D& a, const Vector3D& b) {
    return a.dot(b);
}

Upvotes: 0

Views: 52

Answers (3)

cigien
cigien

Reputation: 60460

You should qualify the member function dot as const as well, otherwise you can't call this member function on a const object:

float dot(Vector3D const& v) const {  // <-- const here

You also need to accept v by const& since you are passing it a const object.

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

In the Vector3D::dot function, neither the object for member function call nor the argument object are modified.

To tell this to the compiler, you should add two consts to your dot definition.

class Vector3D{
public:
    float x, y, z;
    float dot(const /*(1)*/ Vector3D& v) const /*(2)*/ {
        return x * v.x + y * v.y + z * v.z;
    }
}; 
inline float operator *(const Vector3D& a, const Vector3D& b) {
    return a.dot(b);
}

(1) : telling that the argument object is not modified
(2) : telling that the object for member function call is not modified

Upvotes: 0

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123566

You didn't include the error, but it says something like : "cannot call non-const method on const object". Your dot does not modify members and should be declared as const also the argument is not modifed, hence should be const:

class Vector3D{
public:
    float x, y, z;
                                // v---------------- allow to call on const objects
    float dot(const Vector3D& v) const {
            //  ^----------------------------------  pass parameters as const ref
        return x * v.x + y * v.y + z * v.z;
    }
}; 
inline float operator *(const Vector3D& a, const Vector3D& b) {
    return a.dot(b);
}

Upvotes: 0

Related Questions