Home arrow Virus Trojans Worms arrow Constructor & Destructor

Language Translator

Hacking Zone

Hacking Tools
Attacking

Configure Windows

Windows Configuration

Mix Tutorials

Asterisk
Website Building

Novels

Mix Novels

Human Personality

Body Language
Constructor & Destructor Print E-mail
Article Index
Constructor & Destructor
Page 2
Page 3
Page 4
Page 5

Constructor & Destructor : Initialization & Cleanup

 

             

                Chapter 4 made a significant improvement in library use by taking all the scattered components of a typical C library and encapsulating them into a structure (an abstract data type, called a class from now on).This not only provides a single unified point of entry into a library component, but it also hides the names of the functions within the class name. In Chapter 5, access control (implementation hiding) was introduced. This gives the class designer a way to establish clear boundaries for determining what the client programmer is allowed to manipulate and what is off limits. It means the internal mechanisms of a data type’s operation are under the control and discretion of the class designer, and it’s clear to client programmers what members they can and should pay attention to.

                Together, encapsulation and access control make a significant step in improving the ease of library use. The concept of “new data type” they provide is better in some ways than the existing built-in data types from C. The C++ compiler can now provide type-checking guarantees for that data type and thus ensure a level of safety when that data type is being used.

 

                When it comes to safety, however, there’s a lot more the compiler can do for us than C provides. In this and future chapters, you’ll see additional features that have been engineered into C++ that make the bugs in your program almost leap out and grab you, sometimes before you even compile the program, but usually in the form of compiler warnings and errors. For this reason, you will soon get used to the unlikely-sounding scenario that a C++ program that compiles often runs right the first time.

                Two of these safety issues are initialization and cleanup. A large segment of C bugs occur when the programmer forgets to initialize or clean up a variable. This is especially true with C libraries, when client programmers don’t know how to initialize a struct, or even that they must. (Libraries often do not include an initialization function, so the client programmer is forced to initialize the struct by hand.) Cleanup is a special problem because C programmers are comfortable with forgetting about variables once they are finished, so any cleaning up that may be necessary for a library’s struct is often missed.

                In C++, the concept of initialization and cleanup is essential for easy library use and to eliminate the many subtle bugs that occur when the client programmer forgets to perform these activities. This chapter examines the features in C++ that help guarantee proper initialization and cleanup.

 

Guaranteed initialization with the constructor

                Both the Stash and Stack classes defined previously have a function called initialize( ), which hints by its name that it should be called before using the object in any other way. Unfortunately, this means the client programmer must ensure proper initialization. Client programmers are prone to miss details like initialization in their headlong rush to make your amazing library solve their problem. In C++, initialization is too important to leave to the client programmer. The class designer can guarantee initialization of every object by providing a special function called the constructor. If a class has a constructor, the compiler automatically calls that constructor at the point an object is created, before client programmers can get their hands on the object. The constructor call isn’t even an option for the client programmer; it is performed by the compiler at the point the object is defined.

The next challenge is what to name this function. There are two issues. The first is that any name you use is something that can potentially clash with a name you might like to use as a member in the class. The second is that because the compiler is responsible for calling the constructor, it must always know which function to call. The solution Stroustrup chose seems the easiest and most logical: the name of the constructor is the same as the name of the class. It makes sense that such a function will be called automatically on initialization.

Here’s a simple class with a constructor:

class X {
int i;
public:
X(); // Constructor
};

Now, when an object is defined,

void f() {
X a;
// ...
}

the same thing happens as if a were an int: storage is allocated for the object. But when the program reaches the sequence point (point of execution) where a is defined, the constructor is called automatically. That is, the compiler quietly inserts the call to X::X( ) for the object a at the point of definition. Like any member function, the first (secret) argument to the constructor is the this pointer – the address of the object for which it is being called. In the case of the constructor, however, this is pointing to an un-initialized block of memory, and it’s the job of the constructor to initialize this memory properly.

Like any function, the constructor can have arguments to allow you to specify how an object is created, give it initialization values, and so on. Constructor arguments provide you with a way to guarantee that all parts of your object are initialized to appropriate values. For example, if a class Tree has a constructor that takes a single integer argument denoting the height of the tree, then you must create a tree object like this:

Tree t(12);  // 12-foot tree

If Tree(int) is your only constructor, the compiler won’t let you create an object any other way. (We’ll look at multiple constructors and different ways to call constructors in the next chapter.)

                That’s really all there is to a constructor; it’s a specially named function that is called automatically by the compiler for every object at the point of that object’s creation. Despite it’s simplicity, it is exceptionally valuable because it eliminates a large class of problems and makes the code easier to write and read. In the preceding code fragment, for example, you don’t see an explicit function call to some initialize( ) function that is conceptually separate from definition. In C++, definition and initialization are unified concepts – you can’t have one without the other.

            Both the constructor and destructor are very unusual types of functions: they have no return value. This is distinctly different from a void return value, in which the function returns nothing but you still have the option to make it something else. Constructors and destructors return nothing and you don’t have an option. The acts of bringing an object into and out of the program are special, like birth and death, and the compiler always makes the function calls itself, to make sure they happen. If there were a return value, and if you could select your own, the compiler would somehow have to know what to do with the return value, or the client programmer would have to explicitly call constructors and destructors, which would eliminate their safety.

 

Guaranteed cleanup with the destructor

As a C programmer, you often think about the importance of initialization, but it’s rarer to think about cleanup. After all, what do you need to do to clean up an int? Just forget about it. However, with libraries, just “letting go” of an object once you’re done with it is not so safe. What if it modifies some piece of hardware, or puts something on the screen, or allocates storage on the heap? If you just forget about it, your object never achieves closure upon its exit from this world. In C++, cleanup is as important as initialization and is therefore guaranteed with the destructor.

The syntax for the destructor is similar to that for the constructor: the class name is used for the name of the function. However, the destructor is distinguished from the constructor by a leading tilde (~). In addition, the destructor never has any arguments because destruction never needs any options. Here’s the declaration for a destructor:

class Y {
public:
~Y();
};

The destructor is called automatically by the compiler when the object goes out of scope. You can see where the constructor gets called by the point of definition of the object, but the only evidence for a destructor call is the closing brace of the scope that surrounds the object. Yet the destructor is still called, even when you use goto to jump out of a scope. (goto still exists in C++ for backward compatibility with C and for the times when it comes in handy.) You should note that a nonlocal goto, implemented by the Standard C library functions setjmp( ) and longjmp( ), doesn’t cause destructors to be called. (This is the specification, even if your compiler doesn’t implement it that way. Relying on a feature that isn’t in the specification means your code is nonportable.)

Here’s an example demonstrating the features of constructors and destructors you’ve seen so far:

//: C06:Constructor1.cpp
// Constructors & destructors
#include <iostream>
using namespace std;

class Tree {
int height;
public:
Tree(int initialHeight); // Constructor
~Tree(); // Destructor
void grow(int years);
void printsize();
};

Tree::Tree(int initialHeight) {
height = initialHeight;
}

Tree::~Tree() {
cout << "inside Tree destructor" << endl;
printsize();
}

void Tree::grow(int years) {
height += years;
}

void Tree::printsize() {
cout << "Tree height is " << height << endl;
}

int main() {
cout << "before opening brace" << endl;
{
Tree t(12);
cout << "after Tree creation" << endl;
t.printsize();
t.grow(4);
cout << "before closing brace" << endl;
}
cout << "after closing brace" << endl;
} ///:~

Here’s the output of the above program:

before opening brace
after Tree creation
Tree height is 12
before closing brace
inside Tree destructor
Tree height is 16
after closing brace

You can see that the destructor is automatically called at the closing brace of the scope that encloses it.



 
< Prev   Next >
Your Ad Here

RSS socialnet

Add to MyYahoo!
Subscribe in NewsGator Online
Add to Newsburst
Add to Google
Add to My AOL
Add to Pluck
Subscribe in FeedLounge
Add to Windows Live
Add to NetVibes
Subscribe in Rojo
Subscribe in Bloglines
Add to MyMSN
Add to Plusmo for your cellphone
Add to PageFlakes
Add to Technorati
Add to BlinkBits
BargainCouponCode.com: top coupons for anyone, absolutely free