Sams Teach Yourself C in 21 Days

(singke) #1

Housekeeping with Classes ................................................................................


Earlier, you learned that to initially set data values into the class, an init()function was
called. C++ actually provides a mechanism in which you can initialize objects created
with a class at the time they are created. Additionally, a mechanism is in place to do
clean-up at the end of the life of an object. This clean-up is done at the time the object is
destroyed. To help in these situations, C++ provides constructors and destructors.

Starting with Constructors ..................................................................................


A constructor is a specialized member function within a class. The name of the construc-
tor is the same as the name of a class. By default, C++ provides a constructor that sets up
a class. You can, however, create your own constructor. If you do, the default work done
by the compiler will be overridden.
Because a constructor is executed at the time a class is being created, it is perfect for ini-
tializing any data members and for making any allocations you need for a class.

Ending with Destructors ................................................................................


A destructor is also a specialized member function within a class. The destructor has the
same name as the class; however, the destructor also has a tilde (~) before its name. A
destructor is executed as an object is being destroyed. An object is destroyed when it
goes out of scope. For the timeclass, the destructor is called ~time().
A destructor gives you the opportunity to do clean-up. For example, consider a class that
dynamically allocates memory when an object is created from it. A constructor can be
used to do the dynamic allocation. The destructor can be used to free the memory.

Using Constructors and Destructors ..............................................................


Listing B3.6 presents an example of using a constructor and a destructor with a class.
This example dynamically allocates memory in the constructor and releases it in the
destructor. Messages are printed in order for you to see when these member functions are
called. You should note that two new keywords are presented to do the memory alloca-
tion.

LISTINGB3.6 const.cpp. Using constructors and destructors
1: //Using constructors and destructors
2: #include <iostream.h>
3:
4: class value {

684 Bonus Day 3

38 448201x-Bonus3 8/13/02 11:19 AM Page 684

Free download pdf