|
|
|
|
|
|
|
In line 41, pRect is used to set the width of the rectangle to 10. In line 42, pConstRect would be used, but it was declared to point to a constant Rectangle. Therefore, it cannot legally call a non-const member function; it is commented out. On line 34, pConstPtr is declared to be a constant pointer to a rectangle. In other words, the pointer is constant and cannot point to anything else, but the rectangle is not constant. |
|
|
|
|
|
|
|
|
When you declare an object to be const, you are, in effect, declaring that the this pointer is a pointer to a const object. A const this pointer can be used only with const member functions. |
|
|
|
|
|
|
|
|
Constant objects and constant pointers will be discussed again in the next hour, when references to constant objects are discussed. |
|
|
|
|
|
|
|
|
Pointers can be a powerful technique for managing objects on the free store. They bring risks of memory leaks and stray pointers; but, if you are careful, they are safe and effective to use in your programs. |
|
|
|
|
|
|
|
|
You can declare pointers to be constant, and enlist the compiler in helping you find those places in which you use your pointers in ways you had not intended. |
|
|
|
|
|
|
|
|
Q Why should I declare an object as const if it limits what I can do with it? |
|
|
|
|
|
|
|
|
A As a programmer, you want to enlist the compiler in helping you find bugs. One serious bug that is difficult to find is a function that changes an object in ways that aren't obvious to the calling function. Declaring an object const prevents such changes. |
|
|
|
|
|
|
|
|
Q Why should I bother to declare anything on the free store? |
|
|
|
|
|
|
|
|
A Objects on the free store persist after the return of a function. In addition, objects declared on the free store can be used to create complex data structures as explored in Chapter 19, Linked Lists. |
|
|
|
|
|