Using const and Non-const Member Functions

The program of Fig. 9.16 uses class Time from Figs. 9.49.5, but removes const from function printStandard’s prototype and definition so that we can show a compilation error. We instantiate two Time objects—non-const object wakeUp (line 7) and const object noon (line 8). The program attempts to invoke non-const member functions setHour (line 13) and printStandard (line 20) 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 11), a const member function on a non-const object (line 15) and a const member function on a const object (lines 17–18). The error messages generated for non-const member functions called on a const object are shown in the output window.


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

Microsoft Visual C++ compiler error messages:


C:examplesch09Fig09_16_18fig09_18.cpp(13) : error C2662:
   'Time::setHour' : cannot convert 'this' pointer from 'const Time' to
   'Time &'
          Conversion loses qualifiers
C:examplesch09Fig09_16_18fig09_18.cpp(20) : error C2662:
   'Time::printStandard' : cannot convert 'this' pointer from 'const Time' to
   'Time &'
        Conversion loses qualifiers


Fig. 9.16. const objects and const member functions.

A constructor must be a non-const member function, but it can still be used to initialize a const object (Fig. 9.16, line 8). Recall from Fig. 9.5 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 20 in Fig. 9.16 generates a compilation error even though member function printStandard of class Time does not modify the object on which it’s invoked. 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
18.188.44.223