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

CSE 143/AC : 18 July 2000

Uses of const

  1. Symbolic constants:

    Declares a value that cannot change after it is initialized. All symbolic constants must be initialized. Local symbols may be declared const in order to enforce program correctness.

    const double BASE_NATURAL_LOG = 2.718281828459045;
  2. Constant arguments:

    Declares that an argument (or, in the case of const pointers/references, the object to which the argument points) will not be modified in the body of a function:

    class Point { public: int x, y; }; void clam(const Point p, const Point& q) { p.x = 3; // compile error: p declared const q.x = 5; // compile error: q references const Point }
  3. Non-mutating methods:

    By writing const after the full profile of a method in a class, we can declare that it does not modify any class members. Only const methods may be called on const objects.

    struct Point { Point(int init_x, int init_y); int getX() const; // ... };

    Const-ness is "infectious", which is to say that a pointer or reference to a non-const value cannot be passed into a non-const argument or assigned to a non-const variable:

    void oyster( Point& p ); void shrimp( Point p ); const Point p(2, 3); // constant point oyster( p ); // error: cannot "cast" to non-const shrimp( p ); // okay: const objects may be copied

Historical trivia: the reason that certain C++ keywords, such as const and static, have so many different meanings is that C++ had to maintain backwards compatibility with C. Therefore, people were very resistant to adding new keywords; a keyword like immutable or inparam would probably break some old C code. Even const was a struggle (though it has since been adopted into ANSI-standard C as well).


Last modified: Mon Jul 17 23:13:40 PDT 2000