العودة إلى  مدرسة الكمبيوتر   قسم البرمجة    الصفحة الأولى

Destructors

 

“Destructor” functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). Designate a function as a class’s destructor by preceding the class name with a tilde (~). For example, the destructor for class String is declared: ~String().

The destructor is commonly used to “clean up” when an object is no longer necessary. Consider the following declaration of a String class:

#include <string.h>

 

class String

{

public:

    String( char *ch );  // Declare constructor

    ~String();           //  and destructor.

private:

    char *_text;

};

 

// Define the constructor.

String::String( char *ch )

{

    // Dynamically allocate the correct amount of memory.

    _text = new char[strlen( ch ) + 1];

 

    // If the allocation succeeds, copy the initialization string.

    if( _text )

       strcpy( _text, ch );

}

 

// Define the destructor.

String::~String()

{

    // Deallocate the memory that was previously reserved

    //  for this string.

    delete[] _text;

}

In the preceding example, the destructor String::~String uses the delete operator to deallocate the space dynamically allocated for text storage.

 

 طباعة المقال العودة إلى  مدرسة الكمبيوتر   قسم البرمجة    الصفحة الأولى
Syria
سورية
Amrit
عمريت
أرواد
طرطوس
صور من طرطوس
صور من سورية
للسيدات فقط
معجم الكمبيوتر
أدب وفكر
المجلة الطبية
المعلومات العامة
لمحة عن طرطوس
الموضة النسائية
مدرسة الكمبيوتر
 © 2002-2012 LBCInformation Corporation. All rights reserved م حنا عطا لحود.