c++thisclass-methoddatamemberfunction-qualifier

What can a const member function change?


C++ methods allow a const qualifier to indicate that the object is not changed by the member function. But what does that mean? Eg. if the instance variables are pointers, does it mean that the pointers are not changed, or also that the memory to which they point is not changed?

Concretely, here is a minimal example class

class myclass {
  int * data;

  myclass() {
    data = new int[10];
  }

  ~myclass() {
    delete [] data;
  }

  void set(const int index) const {
    data[index] = 1;
  }
};

Does the method set correctly qualify as const? It does not change the member variable data, but it sure does change the content of the array.


Solution

  • Most succinctly, it means that the type of this is const T * inside const member functions, where T is your class, while in unqualified functions it is T *.

    Your method set does not change data, so it can be qualified as const. In other words, myclass::data is accessed as this->data and is of type int * const.