9.11 const Objects and const Member Functions

Let’s see how the principle of least privilege applies to objects. Some objects need to be modifiable and some do not. You may use const to specify that an object is not modifiable and that any attempt to modify the object should result in a compilation error. The statement


const Time noon{12, 0, 0};

declares a const object noon of class Time and initializes it to 12 noon. It’s possible to instantiate const and non-const objects of the same class.

Error-Prevention Tip 9.5

Attempts to modify a const object are caught at compile time rather than causing execution-time errors.

 

Performance Tip 9.3

Declaring variables and objects const when appropriate can improve performance— compilers can perform optimizations on constants that cannot be performed on non-const variables.

C++ disallows member-function calls for const objects unless the member functions themselves are also declared const. This is true even for get member functions that do not modify the object. This is also a key reason that we’ve declared as const all member functions that do not modify the objects on which they’re called.

Common Programming Error 9.3

Defining as const a member function that calls a non-const member function of the class on the same object is a compilation error.

 

Common Programming Error 9.4

Invoking a non-const member function on a const object is a compilation error.

An interesting problem arises for constructors and destructors, each of which typically modifies objects. A constructor must be allowed to modify an object so that the object can be initialized. A destructor must be able to perform its termination housekeeping before an object’s memory is reclaimed by the system. Attempting to declare a constructor or destructor const is a compilation error. The “constness” of a const object is enforced from the time the constructor completes initialization of the object until that object’s destructor is called.

Using const and Non-const Member Functions

The program of Fig. 9.17 uses class Time from Figs. 9.59.6, but removes const from function toStandardString’s prototype and definition so that we can show a compilation error. We create two Time objects—non-const object wakeUp (line 6) and const object noon (line 7). The program attempts to invoke non-const member functions setHour (line 11) and toStandardString (line 15) on the const object noon. In each case, the compiler generates an error message. The program also illustrates the three other member-function-call combinations on objects—a non-const member function on a non-const object (line 10), a const member function on a non-const object (line 12) and a const member function on a const object (lines 13–14). The error messages generated for non-const member functions called on a const object are shown in the output window.

Fig. 9.17 const objects and const member functions.

Alternate View

 1   // Fig. 9.17: fig09_17.cpp
 2   // const objects and const member functions.
 3   #include "Time.h" // include Time class definition
 4
 5   int main() {
 6      Time wakeUp{6, 45, 0}; // non-constant object
 7      const Time noon{12, 0, 0}; // constant object
 8
 9                                   // OBJECT    MEMBER FUNCTION
10      wakeUp.setHour(18);          // non-const non-const
11      noon.setHour(12);            // const     non-const
12      wakeUp.getHour();            // non-const const
13      noon.getMinute();            // const     const
14      noon.toUniversalString();    // const     const
15      noon.toStandardString();     // const     non-const
16   }

Microsoft Visual C++ compiler error messages:


C:examplesch09fig09_17fig09_17.cpp(11): error C2662:
   'void Time::setHour(int)': cannot convert 'this' pointer from 'const Time'
   to 'Time &'
C:examplesch09fig09_17fig09_17.cpp(11): note: Conversion loses qualifiers
C:examplesch09fig09_17fig09_17.cpp(15): error C2662:
   'std::string Time::toStandardString(void)': cannot convert 'this' pointer
   from 'const Time' to 'Time &'
C:examplesch09fig09_17fig09_17.cpp(15): note: Conversion loses qualifiers

A constructor must be a non-const member function, but it can still be used to initialize a const object (Fig. 9.17, line 7). Recall from Fig. 9.6 that the Time constructor’s definition calls another non-const member function—setTime—to perform the initialization of a Time object. Invoking a non-const member function from the constructor call as part of the initialization of a const object is allowed.

Line 15 in Fig. 9.17 generates a compilation error even though member function toStandardString of class Time does not modify the object on which it’s called. The fact that a member function does not modify an object is not sufficient—the function must explicitly be declared const.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset