Understanding Pointers 249
8
The trick to keeping this straight is to look to the right of the keyword constto find out
what is being declared constant. If the type is to the right of the keyword, it is the value
that is constant. If the variable is to the right of the keyword const, it is the pointer vari-
able itself that is constant. The following helps to illustrate this:
const int * p1; // the int pointed to is constant
int * const p2; // p2 is constant, it can’t point to anything else
constPointers and constMember Functions................................................
On Day 6, you learned that you can apply the keyword constto a member function.
When a function is declared 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 constobject, the only methods that you can call with that
pointer are constmethods. Listing 8.10 illustrates this.
LISTING8.10 Using Pointers to constObjects
1: // Listing 8.10 - Using pointers with const methods
2:
3: #include <iostream>
4: using namespace std;
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: void SetWidth(int width) { itsWidth = width; }
14: int GetWidth() const { return itsWidth; }
15:
16: private:
17: int itsLength;
18: int itsWidth;
19: };
20:
21: Rectangle::Rectangle()
22: {
23: itsWidth = 5;
24: itsLength = 10;
25: }
26:
27: Rectangle::~Rectangle()
28: {}
29: