Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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++.

like image 765
itsaboutcode Avatar asked Dec 31 '25 07:12

itsaboutcode


1 Answers

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.

like image 76
bmargulies Avatar answered Jan 01 '26 22:01

bmargulies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!