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 that is called when an object of the class is instantiated. The job of the constructor is to create a valid instance of the class. Creating a valid instance of the class often includes initializing its member data. The constructor is a class method with the same name as the class itself but with no return value. Constructors may or may not have parameters, just like any other method of the class.

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. To write a destructor for the Cat class, you would write:

~Cat();

Default Constructors

When you write


Cat Frisky(5);

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 default constructor is a constructor with 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 define it or you get it as a default from the compiler.

  • If you define 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 define it yourself.

If you fail to define 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 define a constructor, be sure to define a destructor, even if your destructor does nothing. Although it is true that the default destructor would work correctly, it doesn't hurt to define your own, and it makes your code clearer.

Listing 7.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 7.2. Using Constructors and Destructors
 0:   // Demonstrates declaration of a constructor and
 1:   // destructor for the Cat class
 2:  #include <iostream>      // for std::cout
 3:  using std::cout;         // always use std::cout in this file
 4:
 5:  class Cat                // begin declaration of the class
 6:  {
 7:  public:                  // begin public section
 8:      Cat(int initialAge); // constructor
 9:      ~Cat();              // destructor
10:      int GetAge();        // accessor function
11:      void SetAge(int age);// accessor function
12:      void Meow();
13:  private:                 // begin private section
14:      int itsAge;          // member variable
15:  };
16:
17:  // constructor of Cat,
18:  Cat::Cat(int initialAge)
19:  {
20:      itsAge = initialAge;
21:  }
22:
23:  // destructor, takes no action
24:  Cat::~Cat()
25:  {
26:
27:  }
28:
29:  // GetAge, Public accessor function
30:  // returns value of itsAge member
31:  int Cat::GetAge()
32:  {
33:      return itsAge;
34:  }
35:
36:  // Definition of SetAge, public
37:  // accessor function
38:  void Cat::SetAge(int age)
39:  {
40:      // set member variable itsAge to
41:      // value passed in by parameter age
42:      itsAge = age;
43:  }
44:
45:  // definition of Meow method
46:  // returns: void
47:  // parameters: None
48:  // action: Prints "meow" to screen
49:  void Cat::Meow()
50:  {
51:      cout << "Meow.
";
52:  }
53:
54:  // create a cat, set its age, have it
55:  // meow, tell us its age, then meow again.
56:  int main()
57:  {
58:      Cat Frisky(5);
59:      Frisky.Meow();
60:      cout << "Frisky is a cat who is " ;
61:      cout << Frisky.GetAge() << " years old.
";
62:      Frisky.Meow();
63:      Frisky.SetAge(7);
64:      cout << "Now Frisky is " ;
65:      cout << Frisky.GetAge() << " years old.
";
66:      return 0;
67:  }


Meow,
Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.

Listing 7.2 is similar to 7.1, except that line 8 adds a constructor that takes an integer. Line 9 declares the destructor, which takes no parameters. Destructors never take parameters, and neither constructors nor destructors return a value—not even void.


Lines 18–21 show the implementation of the constructor, which is similar to the implementation of the SetAge() accessor function. There is no return value.

Lines 24–27 show the implementation of the destructor ~Cat(). This function does nothing, but you must include the definition of the function if you define it in the class declaration.

Line 58 contains the definition of a Cat object, Frisky. The value 5 is passed in to Frisky's constructor. There is no need to call SetAge(), because Frisky was created with the value 5 in its member variable itsAge, as shown in line 61. In line 63, Frisky's itsAge variable is reassigned to 7. Line 65 prints the new value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.167