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!

Recommended Answers

All 3 Replies

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

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
    }
};

Thanks! That's very clear and concise.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.