const (Constant) Objects and const Member Functions

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. The program of Figs. 2.1-2.4 modifies class Time by making its get functions and printUniversal function const. 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.
\includegraphics[scale=0.45]{figures//img7.5.ps}
\includegraphics[scale=0.45]{figures//img7.6.ps}
Figure 2.2: Time class member-function definitions, including const member functions. (part 1 of 2)
\includegraphics[scale=0.45]{figures//img7.7.ps}
\includegraphics[scale=0.45]{figures//img7.8.ps}
Figure 2.3: Time class member-function definitions, including const member functions. (part 2 of 2)
\includegraphics[scale=0.45]{figures//img7.9.ps}
\includegraphics[scale=0.45]{figures//img7.10.ps}
Figure 2.4: const objects and const member functions.
\includegraphics[scale=0.45]{figures//img7.11.ps}
\includegraphics[scale=0.45]{figures//img7.12.ps}
Figure 2.5: Member initializer used to initialize a constant of a built-in data type. (part 1 of 2)
\includegraphics[scale=0.45]{figures//img7.14.ps}
\includegraphics[scale=0.45]{figures//img7.15.ps}
Figure 2.6: Member initializer used to initialize a constant of a built-in data type. (part 2 of 2)
\includegraphics[scale=0.43]{figures//img7.16.ps}
Figure 2.7: Erroneous attempt to initialize a constant of a built-in data type by assignment. (part 1 of 2)
\includegraphics[scale=0.45]{figures//img7.17.ps}
\includegraphics[scale=0.45]{figures//img7.18.ps}
Figure 2.8: Erroneous attempt to initialize a constant of a built-in data type by assignment. (part 2 of 2)
\includegraphics[scale=0.43]{figures//img7.19.ps}
2004-12-28