|
|
|
|
|
|
|
void SetAge(int anAge);
int GetAge(); |
|
|
|
|
|
|
|
|
SetAge() cannot be const because it changes the member variable itsAge. GetAge(), on the other hand, can and should be const because it doesn't change the class at all. It simply returns the current value of the member variable itsAge. Therefore, the declaration of these functions should be written like this: |
|
|
|
|
|
|
|
|
void SetAge(int anAge);
int GetAge() const; |
|
|
|
|
|
|
|
|
If you declare a function to be const and then the implementation of that function changes the object (by changing the value of any of its members), the compiler will flag it as an error. For example, if you wrote GetAge() so that it kept count of the number of times that the Cat was asked its age, it would generate a compiler error. You would be changing the Cat object by calling this method. |
|
|
|
|
|
|
|
|
Use const whenever possible. Declare member functions to be const whenever they should not change the object. This lets the compiler help you find errors; it's faster and less expensive than doing it yourself. |
|
|
|
|
|
|
|
|
|
It is good programming practice to declare as many methods to be const as possible. Each time you do, you enable the compiler to catch your errors, instead of letting your errors become bugs that will show up when your program is running. |
|
|
|
|
|
|
|
|
Interface Versus Implementation. |
|
|
|
|
|
|
|
|
As you've learned, clients are the parts of the program that create and use objects of your class. You can think of the interface to your classthe class declarationas a contract with these clients. The contract tells what data your class has available and how your class will behave. |
|
|
|
|
|
|
|
|
For example, in the Cat class declaration, you create a contract that every Cat will know and be able to retrieve its own age, that you can initialize that age at construction and set it or retrieve it later, and that every Cat will know how to Meow(). |
|
|
|
|
|
|
|
|
If you make GetAge() a const function (as you should), the contract also promises that GetAge() won't change the Cat on which it is called. |
|
|
|
|
|