Lets say that I have a
class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.
If you want the compiler to enforce this, then declare the member function
const:A
constfunction is not allowed to modify its member variables, and can only call otherconstmember functions (either its own, or those of its member variables).The exception to this rule is if the member variable is declared as
mutable. [Butmutableshould not be used as a general-purposeconstworkaround; it’s only really meant for when situations where the “observable” state of an object should beconst, but internal implementation (such as reference-counting or lazy evaluation) still needs to change.]Note also that
constdoes not propagate through e.g. pointers.So in summary: