const

const: Immutable Variable

Already possible in C: immutable variables

const struct point *p;
p->x = 7;       // ERROR!!

Variables ⟶ modification impossible

void f(const struct point *p)
{
    p->x = 7;   // ERROR!!
}

Parameter ⟶ modification impossible

const: Methods (1)

  • const methods promise to the compiler not to modify the object

  • No promise ⟶ compiler has to assume that the method modifies the object

class point
{
public:
    int x() { return _x; }
    int y() { return _y; }
private:
    int _x;
    int _y;
};
void f(const point *p)
{
    cout << p->x();      // ERROR!!
}

const: Methods (2)

class point
{
public:
    int x() const { return _x; }
    int y() const { return _y; }
private:
    int _x;
    int _y;
};
  • const pollution” ⇔ “being correct is very cumbersome”

  • const correctness”: best possible state

  • Nice goodie offered by the language