[   ^ to index...   |   <-- previous   |   next -->   ]

Complications of const

  1. Sometimes, it is advantageous to declare certaim data members of a class to be read-only. This can be done using const members:

    struct Point { Point(init_x, init_y); const int x, y; };

    This makes the Point immutable, which has certain nice properties for software engineering and understanding. Const members must always be initialized using initializer list syntax.

  2. In rare cases, one can eliminate the const-ness of an object using the const_cast mechanism:

    const int * whale = new int(5); // Evil and wrong int * orca = const_cast<int*>(whale); *orca = 4;
  3. Q: Does declaring an object const mean that you can always rely on it to stay the same value?

    A: No. First, evil programmers may use pointers and and const_cast to defeat constness. Second, when doing low-level programming, it is possible that you may declare data const to prevent yourself from modifying data, while understanding that the machine may modify it as a side effect of some other operation (e.g., the buffer memory in a network card).

  4. Sometimes, there will be a legitimate reason to have certain members of a class remain mutable, even when the rest of the object is const (e.g.: a cache for a search engine's dictionary). We can declare certain members "always mutable" with the mutable keyword:

    class LineSegment { double getMagnitude(); private: int x0, y0, x1, y1; // We could compute this value on demand, // even for const objects. mutable double magnitude; };

Last modified: Mon Jul 17 23:34:26 PDT 2000