Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 157

6


Lines 24–26 show the implementation of the destructor ~Cat(). For now, this function
does nothing, but you must include the definition of the function if you declare it in the
class declaration. Like the constructor and other methods, this is also preceded by the
class name. Like the constructor, but differing from other methods, no return time or
parameters are included. This is standard for a destructor.
Line 57 contains the definition of a Catobject,Frisky. The value 5 is passed in to
Frisky’s constructor. No need exists to call SetAge()because Friskywas created with
the value 5 in its member variable itsAge, as shown on line 60. On line 62,Frisky’s
itsAgevariable is reassigned to 7. Line 64 prints the new value.

DOuse constructors to initialize your
objects.
DOadd a destructor if you add a
constructor.

DON’Tgive constructors or destructors a
return value.
DON’Tgive destructors parameters.

DO DON’T


Including const Member Functions ....................................................................


You have used the constkeyword to declare variables that would not change. You can
also use the constkeyword with member functions within a class. If you declare a class
method const, you are promising that the method won’t change the value of any of the
members of the class.
To declare a class method constant, put the keyword constafter the parentheses enclos-
ing any parameters, but before the semicolon ending the method declaration. For
example,
void SomeFunction() const;
This declares a constant member method called SomeFunction()that takes no arguments
and returns void. You know this will not change any of the data members within the
same class because it has been declared const.
Accessor functions that only get values are often declared as constant functions by using
the constmodifier. Earlier, you saw that the Catclass has two accessor functions:
void SetAge(int anAge);
int GetAge();
SetAge()cannot be constbecause it changes the member variable itsAge. GetAge(),on
the other hand, can and should be constbecause it doesn’t change the class at all.
Free download pdf