Sams Teach Yourself C++ in 21 Days

(singke) #1
GetAge()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 the implementation of that function changes
the object by changing the value of any of its members, the compiler flags it as an error.
For example, if you wrote GetAge()in such a way that it kept count of the number of
times that the Catwas asked its age, it would generate a compiler error. This is because
you would be changing the Catobject when the method was called.
It is good programming practice to declare as many methods to be constas 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 ........................................................................


Clients are the parts of the program that create and use objects of your class. You can
think of the public interface to your class—the class declaration—as a contract with
these clients. The contract tells how your class will behave.
In the Catclass declaration, for example, you create a contract that every Cat’s age can
be initialized in its constructor, assigned to by its SetAge()accessor function, and read
by its GetAge()accessor. You also promise that every Catwill know how to Meow().
Note that you say nothing in the public interface about the member variable itsAge; that
is an implementation detail that is not part of your contract. You will provide an age
(GetAge()) and you will set an age (SetAge()), but the mechanism (itsAge) is invisible.
If you make GetAge()a constfunction—as you should—the contract also promises that
GetAge()won’t change the Caton which it is called.
C++ is strongly typed, which means that the compiler enforces these contracts by giving
you a compiler error when you violate them. Listing 6.5 demonstrates a program that
doesn’t compile because of violations of these contracts.

158 Day 6


CAUTION Listing 6.5 does not compile!
Free download pdf