Disallow any member function to change its data members in C++ Class

c++

Solution

Make all the member functions `const`. That's the only mechanism for the job, and it works just fine. If you also make them `private` you're completely covered.

If for some reason you feel compelled to mark them protected, then things are more complicated.

You will need to make the individual fields `const`, and that will in turn require you to initialize them via the member initialization list, or a `const_cast` of this in the constructor. Or maybe a mutable ctor, but I'm not sure there is such a thing.

Problem

So how i can do this? So that no member function can change the value of its data members once object has been initialized in C++.

Original source