< previous page page_95 next page >

Page 95
you invoke the constructor for Cat that takes one parameter (in this case, the value 5). If, however, you write
Cat Frisky;
the compiler allows you to leave the parentheses off and calls the default constructor, the constructor that takes no parameters.
Constructors Provided by the Compiler
If you declare no constructors at all, the compiler will create a default constructor for you. (Remember, the default constructor is the constructor that takes no parameters.)
The default constructor the compiler provides takes no action; it is as if you had declared a constructor that took no parameters and whose body was empty.
There are two important points to note about this:
The default constructor is any constructor that takes no parameters, whether you declare it or you get it for free from the compiler.
If you declare any constructor (with or without parameters), the compiler will not provide a default constructor for you. In that case, if you want a default constructor, you must declare it yourself.
If you fail to declare a destructor, the compiler will also give you one of those, and this too will have an empty body and will do nothing.
As a matter of form, if you declare a constructor, be sure 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, and it makes your code clearer.
Listing 6.2 rewrites the Cat class to use a constructor to initialize the Cat object, setting its age to whatever initial age you provide. It also demonstrates where the destructor is called.
LISTING 6.2 USING CONSTRUCTORS AND DESTRUCTORS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:   // Demonstrates declaration of a constructor and
2:   // destructor for the Cat class
3:
4:   #include <iostream.h>       // for cout
5:
6:   class Cat                   // begin declaration of the class
7:   {
8:   public:                    // begin public section
9:     Cat(int initialAge);     // constructor
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_95 next page >

If you like this book, buy it!