2.14.  const Member Functions

[ fromfile: constmembers.xml id: constmembers ]

When a class member function X::f() is invoked through an object x

x.f(); 

we refer to x as the host object.

The const keyword has a special meaning when it is applied to a (non-static) class member function. Placed after the parameter list, const becomes part of the function signature and guarantees that the function will not change the state of the host object.

A good way to look at the way const modifies member functions is to realize that each non-static member function has an implicit parameter, named this, which is a pointer to the host object. When we declare a member function to be const, we are telling the compiler that, as far as the function is concerned, this is a pointer to const.

To explain how const changes the way a function is invoked, we look at how the original C++ to C preprocessor dealt with member functions. Since C did not support overloaded functions or member functions, the preprocessor translated the function into a C function with a “mangled” name, that distinguished itself from other functions by encoding the full signature in the name. The mangling process also added an extra implicit parameter to the parameter list: this, a pointer to the host object. Example 2.20 shows how member functions might be seen by a linker after a translation into C:

Example 2.20. src/const/constmembers.cpp

#include <iostream>

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;
    }
    void print() const {  2
        using namespace std;
        cout << "[" << m_X << "," << m_Y << "]";
        m_X = 5;  3
    }
  private:
    int m_X, m_Y;
};

int main() {
    Point p(1,1);
    const Point q(2,2);
    p.set(4,4);  4
    p.print();
    q.set(4,4);  5
    return 0;
}

1

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

2

C version: _Point_print_void_const(const Point* this)

3

error: this->m_X = 5, *this is const

4

okay to reassign p

5

Error! const object cannot call non-const methods

In a real compiler, the mangled names for set and print would be compressed significantly, to save space and hence be less understandable to a human reader.

We can think of the const in the signature of print() as a modifier of the invisible this parameter that points to the host object. This means that the memory pointed to by this cannot be changed by the action of the print() function. The reason that the assignment x = 5; produces an error is that it is equivalent to this->x = 5;. The assignment violates the rules of const.