-1

Hi all,

Maybe you can help me with this...

in the code

float dot(const Vec3& v) const { return (x * v.x) + (y * v.y) + (z * v.z);}

What is the purpose of the keyword const? Why in the case of

Vec3 operator=(const Vec3& v) const { x = v.x; y = v.y; z = v.z; return *this;}

the second const is invalid?

Thanks!

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by jakesee
0

having const after a member function means that, that function will not
and shall not change any of its variables.

0

having const after a member function means that, that function will not
and shall not change any of its variables.

This is misleading. The method can change any of its local variables and non-const parameters, but it cannot change the state of the object. That means non-mutable data members of the class cannot be changed in a const method:

class A {
public:
    int nonmut;
    mutable int mut;

    void test(int arg) const
    {
        int local;

        local = 0; // OK
        arg = 0; // OK
        mut = 0; // OK
        nonmut = 0; // error
    }
};
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.