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 objectNo 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 stateNice goodie offered by the language