Changing the value of a data member in a const method via its non-const argument in C++: is it valid or not?

The following code compiles successfully both on clang 11.1.0 and gcc 11.1.0 (with -std=c++17 -Wall -Wextra -Werror -pedantic-errors flags):

#include <iostream>

struct Foo
{
    int x{42};

    void bar(int& y) const
    {
        y = 108;
    }
};

int main() {
    Foo foo;
    std::cout << "foo.x = " << foo.x << std::endl;
    foo.bar(foo.x);
    std::cout << "foo.x = " << foo.x << std::endl;
}

This code gives the following output (as expected):

foo.x = 42
foo.x = 108

Is this code valid according to the C++ standard or not?

Source: Windows Questions C++

LEAVE A COMMENT