Search code examples
c++const-correctness

Why are we able to change class object inside const member function


Vector2 Add (const Vector2& other) const
{
    return Vector2(x+ other.x, y+ other.y);
}

The function is a member of the Vector2 class.

If the function is const meaning that it promises not to transform the class, why do we then return that type but can still add stuff to it? I'm genuinely confused by this. Need some clarity, thanks.


Solution

  • why do we then return that type but can still add stuff to it?

    You're not actually modifying the current class object in any way. Instead when you wrote Vector2(x+ other.x, y+ other.y) you're creating another object of the class type using the parameterized ctor with x+ other.x and y+ other.y as arguments and then returning that another object.