< previous page page_157 next page >

Page 157
New Term: pTwo is a constant pointer to an integer. The integer can be changed, but pTwo can't point to anything else. A constant pointer can't be reassigned. That means you can't write
pTwo = &x
New Term: pThree is a constant pointer to a constant integer. The value that is pointed to can't be changed, and pThree can't be changed to point to anything else.
Draw an imaginary line just to the right of the asterisk. If the word const is to the left of the line, that means the object is constant. If the word const is to the right of the line, the pointer itself is constant.
const int * p1;  // the int pointed to is constant
int * const p2;  // p2 is constant, it can't point to anything else
const Pointers and const Member Functions
In hour 6, Basic Classes, you learned that you can apply the keyword const to a member function. When a function is declared as const, the compiler flags as an error any attempt to change data in the object from within that function.
If you declare a pointer to a const object, the only methods that you can call with that pointer are const methods. Listing 10.5 illustrates this.
LISTING 10.5 USING POINTERS TOconst OBJECTS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:      // Listing 10.5
 2:      // Using pointers with const methods
 3:
 4:      #include <iostream.h>
 5:
 6:      class Rectangle
 7:      {
 8:      public:
 9:           Rectangle();
10:           ~Rectangle();
11:           void SetLength(int length) { itsLength = length; }
12:           int GetLength() const { return itsLength; }
13:
14:           void SetWidth(int width) { itsWidth = width; }
15:           int GetWidth() const { return itsWidth; }
16:
17:     private:
18:           int itsLength;
19:           int itsWidth;
20:     };
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_157 next page >

If you like this book, buy it!