Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 155

6


Also as a matter of form, if you declare a constructor, be certain to declare a destructor,
even if your destructor does nothing. Although it is true that the default destructor would
work correctly, it doesn’t hurt to declare your own. It makes your code clearer.
Listing 6.4 rewrites the Catclass to use a nondefault constructor to initialize the Cat
object, setting its age to whatever initial age you provide, and it demonstrates where the
destructor is called.

LISTING6.4 Using Constructors and Destructors


1: // Demonstrates declaration of constructors and
2: // destructor for the Cat class
3: // Programmer created default constructor
4: #include <iostream> // for cout
5:
6: class Cat // begin declaration of the class
7: {
8: public: // begin public section
9: Cat(int initialAge); // constructor
10: ~Cat(); // destructor
11: int GetAge(); // accessor function
12: void SetAge(int age); // accessor function
13: void Meow();
14: private: // begin private section
15: int itsAge; // member variable
16: };
17:
18: // constructor of Cat,
19: Cat::Cat(int initialAge)
20: {
21: itsAge = initialAge;
22: }
23:
24: Cat::~Cat() // destructor, takes no action
25: {
26: }
27:
28: // GetAge, Public accessor function
29: // returns value of itsAge member
30: int Cat::GetAge()
31: {
32: return itsAge;
33: }
34:
35: // Definition of SetAge, public
36: // accessor function
37: void Cat::SetAge(int age)
38: {
39: // set member variable itsAge to
Free download pdf