Is there a way in C ++ to make sure that a member function of a class does not change any data element of the class?

Suppose i have

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 do a compiler check that contains isnt changing the word vector. Ofc is just an example with one member of the class data, I would like it to work with any number of data members. Postscript I know that I don’t have an audience: and it’s closed: I deliberately abandoned the code for a shorter and clearer problem.

+3
source share
5 answers

If you want the compiler to perform this action, declare a member function const:

bool contains(string word) const
{
    ...
}

A const - - const ( , -).

- - ​​ mutable. [ mutable const ; , "" const, ( ) - .]

, const , , .

, :

class Thingy
{
public:
    void apple() const;
    void banana();
};

class Blah
{
private:
    Thingy t;
    int *p;
    mutable int a;

public:
    Blah() { p = new int; *p = 5; }
    ~Blah() { delete p; }

    void bar() const {}
    void baz() {}

    void foo() const
    {
        p = new int;  // INVALID: p is const in this context
        *p = 10;      // VALID: *p isn't const

        baz();        // INVALID: baz() is not declared const
        bar();        // VALID: bar() is declared const

        t.banana();   // INVALID: Thingy::banana() is not declared const
        t.apple();    // VALID: Thingy::apple() is declared const

        a = 42;       // VALID: a is declared mutable
    }
};
+16

const:

bool contains(string word) const
//                        ^^^^^^

: - const!:) : const , :

void foo(const Dictionary& dict){
  // 'dict' is constant, can't be changed, can only call 'const' member functions
  if(dict.contains("hi")){
    // ...
  }
  // this will make the compiler error out:
  dict.addWord("oops");
}
+6

"const" :

bool contains(string word) const
// ...

, - , . , , ( word std::string const&).

+2

const:

void addWord(string word) const { /... }

- , . , const , const.

+2

- const:

bool contains(string word) const
{
//...
}
+1

All Articles