Some objects need to be modifiable and some do not. The programmer may use keyword const to specify that an object is not modifiable and that any attempt to modify the object should result in a compiler error.
- Principle of least privilege; Only allow modification of necessary objects
- Keyword const
- Specify object not modifiable
- Compiler error if attempt to modify const object
- Example
- const Time noon( 12, 0, 0 );
- Declares const object noon of class Time
- Initializes to 12
- const member functions
- Member functions for const objects must also be const; Cannot modify object
- Specify const in both prototype and definition
- Prototype; After parameter list
- Definition; Before beginning left brace
- Constructors and destructors
- Cannot be const
- Must be able to modify objects
- Constructor; Initializes objects
- Destructor; Performs termination housekeeping
The program of Figs. 2.1-2.4 modifies class Time by making its get functions and printUniversal function const.
- Member initializer syntax
- Initializing with member initializer syntax
- Can be used for; All data members
- Must be used for
- const data members
- Data members that are references
Figs. 2.4-2.6 introduces using member initializer syntax. Figs. 2.7-2.8 illustrates the compiler errors for a program that attempts to initialize const data member increment with an assignment statement in the Increment constructor's body rather than with a member initializer.
Figure 2.1:
Time class definition with const member functions.
|
Figure 2.2:
Time class member-function definitions, including const member functions. (part 1 of 2)
|
Figure 2.3:
Time class member-function definitions, including const member functions. (part 2 of 2)
|
Figure 2.4:
const objects and const member functions.
|
Figure 2.5:
Member initializer used to initialize a constant of a built-in data type. (part 1 of 2)
|
Figure 2.6:
Member initializer used to initialize a constant of a built-in data type. (part 2 of 2)
|
Figure 2.7:
Erroneous attempt to initialize a constant of a built-in data type by assignment. (part 1 of 2)
|
Figure 2.8:
Erroneous attempt to initialize a constant of a built-in data type by assignment. (part 2 of 2)
|
2004-07-29