About const

Question: Please explain const again!

Answer:

  1. You never need to use const in your own class definitions. If a class will work with it, it will work without it. However, if you are using a class that declares parameters or return values as const, you must comply with those restrictions.

  2. You use const to explicitly state your intentions: if your intention is that the variable will not change, then you should define it as a const, and no one will be able to change it.

  3. The most common use of const is at the beginning of a function, to declare local variables which will be constant throughout the execution of one call on that function, but the value of the constant depends on one of the parameters.

  4. All global variables should be const, if they are used at all. You can do things with const global variables that you cannot do with #define (initialize constant objects of structured types).

  5. The proper use of const can be a powerful documentation technique. When you are using classes defined by someone else, you often see only the declarations and prototypes of the public members of the class. It is very important to know which of the members are constant and which functions do not modify their parameters.

  6. There are three places the keyword const can appear in a function prototype in C++:
    1. before the function name
    2. before one of the parameters in the parameter list.
    3. between the end of the parameter list and the ; that ends the prototype.

  7. Everywhere a prototype contains a const, the matching function definition must have a matching const. Here are the rules that apply to writing const in a function definition:
    1. const should be used for most return values that are pointers or references. This restricts what the caller can do with the function result; the caller cannot use the result to modify value it points at. Example:
    2. const is used for a parameter declared as a * type or an & type. It means that the function cannot modify that parameter. If used on an ordinary value parameter, it provides no extra protection. This declaration does not restrict the caller; the actual argument in a call does not need to be const.
    3. const can be written before the { that opens the function body. This means that the function does not modify the implied parameter.
Last updated: 1/4/04