2.13.  const Member Functions

[ fromfile: constmembers.xml id: constmembers ]

Example 2.21. src/const/constmembers/constmembers.cpp

#include <QTextStream>
#include <QString>

class Point {
  public:
    Point(int px, int py)
       : m_X(px), m_Y(py) {}

    void set(int nx, int ny) {      1
        m_X = nx;
        m_Y = ny;
    }
    QString toString() const {      2
       // m_X = 5;                  3
        m_Count++;                  4
        return QString("[%1,%2]").arg(m_X).arg(m_Y);
    }
  private:
    int m_X, m_Y;
    mutable int m_Count;            5
};


int main() {
   QTextStream cout(stdout);
   Point p(1,1);
   const Point q(2,2);
   p.set(4,4);                      6
   cout << p.toString() << endl;
   //q.set(4,4);                    7
   return 0;
}

1

C version: _Point_set_int_int(Point* this, int nx, int ny).

2

C version: _Point_toString_string_const(const Point* this).

3

Error: this->m_X = 5, *this is const.

4

Okay, member is mutable.

5

mutable can be changed in a const method.

6

Okay to reassign p.

7

Error! const object cannot call non-const methods.


Suppose that you need to work with a project that contains classes that do not use const correctly. When you start to add const to member functions, parameters, and pointers that need it, you may find that those changes generare a cascade of compiler errors that prevent you from building the project until const has been correctly added throughout the project. When const has finally been added to all the correct places, you can say that your classes are const correct.