< previous page page_94 next page >

Page 94
Line 44 begins the body of the program with the familiar main() function. In this case, it takes no arguments and returns void. In line 46, main() declares a Cat named Frisky. In line 47, the value 5 is assigned to the itsAge member variable by way of the SetAge() accessor method. Note that the method is called by using the class name (Frisky) followed by the member operator (.) and the method name (SetAge()). In this same way, you can call any of the other methods in a class.
Line 48 calls the Meow() member function, and line 49 prints a message using the GetAge() accessor. Line 51 calls Meow() again.
Constructors and Destructors.
There are two ways to define an integer variable. You can define the variable and then assign a value to it later in the program. For example:
int Weight;            // define a variable
                     //  other code here
Weight = 7;           //  assign it a value
Or you can define the integer and immediately initialize it. For example:
int Weight = 7;        // define and initialize to 7
Initialization combines the definition of the variable with its initial assignment. Nothing stops you from changing that value later. Initialization ensures that your variable is never without a meaningful value.
How do you initialize the member data of a class? Classes have a special member function called a constructor. The constructor can take parameters as needed, but it cannot have a return valuenot even void. The constructor is a class method with the same name as the class itself.
Whenever you declare a constructor, you'll also want to declare a destructor. Just as constructors create and initialize objects of your class, destructors clean up after your object and free any memory you might have allocated. A destructor always has the name of the class preceded by a tilde (~). Destructors take no arguments and have no return value. Therefore, the Cat declaration includes
~Cat();
Default Constructors
New Term: A constructor with no parameters is called a default constructor. When you write
Cat Frisky(5);

 
< previous page page_94 next page >

If you like this book, buy it!