Defining Constructors and Destructors


In this section, you will see how to define constructor and destructor functions for a class. Let’s start at the beginning with constructors.

Defining Constructors

A constructor is a special member function that is called automatically when an object is created. The purpose of the constructor is to initialize the object to bring it into an operational state. You declare the prototype for the constructor in the class definition. The following example declares a simple constructor for the CreditCardAccount class:

class CreditCardAccount { public: CreditCardAccount(); // ... Other members, as before };

There are several important points to notice here. First, a constructor must have the same name as the class; this is how the compiler recognizes it as a constructor. Also, a constructor cannot specify a return type, not even void. If you do specify a return type for a constructor, you will get a compiler error.

You can implement the constructor in the source file as follows:

CreditCardAccount::CreditCardAccount() { accountNumber = 1234; currentBalance = 0; creditLimit = 3000; }

This simple constructor will initialize every new CreditCardAccount object with the same values. A more realistic approach is to define a constructor that takes parameters to allow each object to be initialized with different values.

Note

You can provide any number of constructors in a class, as long as each constructor has a distinct parameter list. This is an example of function overloading.

In this exercise, you will add a constructor to your CreditCardAccount class. The constructor will take two parameters specifying the account number and credit limit for the new account. The current balance will always be initialized to 0 for each new account, so there is no need to supply a parameter for this data member.

  1. Continue using the project from the previous exercise.

  2. Open CreditCardAccount.h, and declare a public constructor as follows:

    class CreditCardAccount { public: CreditCardAccount(long number, double limit); // ... Other members, as before };
    Tip

    Make sure that the constructor is public. If you make it private by mistake, you won’t be able to create CreditCardAccount objects in your program.

  3. Open CreditCardAccount.cpp, and implement the constructor as follows:

    CreditCardAccount::CreditCardAccount(long number, double limit) { accountNumber = number; creditLimit = limit; currentBalance = 0.0; }

  4. Open CreditOrganizer.cpp. Modify the statement that creates the CreditCardAccount object as follows:

    myAccount = new CreditCardAccount(12345, 2500); 

    This statement creates a new CreditCardAccount object and passes the values 12345 and 2500 into the CreditCardAccount constructor. The constructor uses these parameter values to initialize the accountNumber and creditLimit data members, respectively.

  5. Build the program, and fix any compiler errors.

  6. Run the program. The program now displays meaningful information for the CreditCardAccount object.

    click to expand

start sidebar
Member Initialization Lists

There’s an alternative syntax for initializing data members in a constructor using a member initialization list as follows:

CreditCardAccount::CreditCardAccount(long number, double limit) : accountNumber(number), creditLimit (limit), currentBalance(0.0) { }

The colon on the second line is followed by a comma-separated list of data members. For each data member, an initial value is provided in parentheses.

For simple initialization, it doesn’t matter whether you use a member initialization list or simply initialize members in the constructor body. However, there are some situations where you have to use a member initialization list. You’ll see such an example in Chapter 8, when you learn about inheritance.

end sidebar

Defining Destructors

A destructor is a special member function that is called automatically when an object is about to be destroyed. The purpose of the destructor is to tidy up the object. For example, the destructor might deallocate additional memory allocated by the object, release resources owned by the object, close database connections opened by the object, and so on.

Note

Only unmanaged classes have destructors. In managed classes, the .NET garbage collector deals with clearing up unused objects; you don’t play a part in object destruction, so you don’t supply a destructor.

You declare the prototype for the destructor in the class definition. The following example declares the destructor for the CreditCardAccount class:

class CreditCardAccount { public: ~CreditCardAccount(); // ... Other members, as before };

The destructor starts with a tilde (~) and has the same name as the class. The destructor does not have a return type and cannot take any parameters. This implies that you can have only one destructor in a class.

You can implement the destructor in the source file as follows:

CreditCardAccount::~CreditCardAccount() { Console::Write(S"Account being destroyed: "); Console::WriteLine(accountNumber); Console::Write(S"Closing balance: "); Console::WriteLine(currentBalance); }

This simple destructor displays status information about a CreditCardAccount object just before it is destroyed.

In this exercise, you will add a destructor to your CreditCardAccount class. The destructor will display a status message describing the object that is being destroyed.

  1. Continue using the project from the previous exercise.

  2. Open CreditCardAccount.h, and declare a public destructor as follows:

    class CreditCardAccount { public: ~CreditCardAccount(); // ... Other members, as before }; 
    Tip

    Make sure the destructor is public, just like the constructor.

  3. Open CreditCardAccount.cpp, and implement the destructor as follows:

    CreditCardAccount::~CreditCardAccount() { Console::Write(S"Account being destroyed: "); Console::WriteLine(accountNumber); Console::Write(S"Closing balance: "); Console::WriteLine(currentBalance); }
  4. Build the program, and fix any compiler errors.

  5. Run the program. As before, the program creates a CreditCardAccount object, invokes its member functions, and then deletes it. When the CreditCardAccount object is deleted, the destructor is called implicitly to display the closing status of the CreditCardAccount object.

    click to expand




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net