< previous page page_109 next page >

Page 109
Q&A
Q If using a const function to change the class causes a compiler error, why shouldn't I just leave out the word const and be sure to avoid errors?
A If your member function logically shouldn't change the class, using the keyword const is a good way to enlist the compiler in helping you find silly mistakes. For example, GetAge() might have no reason to change the Cat class, but if your implementation has this line
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
if (itsAge = 100) cout << Hey! You're 100 years old\n;
declaring GetAge() to be const causes this code to be flagged as an error. You meant to check whether itsAge is equal to 100, but instead you inadvertently assigned 100 to itsAge. Because this assignment changes the class, and you said this method would not change the class, the compiler is able to find the error.
This kind of mistake can be hard to find just by scanning the codethe eye often sees only what it expects to see. More importantly, the program might appear to run correctly, but itsAge has now been set to a bogus number. This will cause problems sooner or later.
Q Is there ever a reason to use a structure in a C++ program?
A Many C++ programmers reserve the struct keyword for classes that have no functions. This is a throwback to the old C structures, which could not have functions. Frankly, I find it confusing and poor programming practice. Today's methodless structure might need methods tomorrow. Then you'll be forced either to change the type to class or to break your rule and end up with a structure with methods.

 
< previous page page_109 next page >

If you like this book, buy it!