c++

Destructor

When and how to use destructor?

1
2
3
4
5
6
~Mystring()
{
cout << "invoking destructor, clearing up" << end;
if(buffer != NULL)
delete [] buffer;
}

Whenever an object is out of scope or is deleted via and then destroyed, system call the Destructor.

When using <char*> buffer area, you must control the memory allocation and release by yourself, I do not recommend it, instead of using < std::string >, which is class tool, they make the most of Constructor and Destructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Mystring //When you use <char*>, you can do like this which is similar to <std::String>
{
private:
char* buffer;
public:
Mystring(const char* inistString) //Constructor
{
if(initString != NULL)
{
buffer = new char(strlen(initString) + 1); //Allocating memory
strcpy(buffer, initString);
}
else
buffer = NULL;
}
~Mystring() //Destructor will be invoked when object is over
{
cout << "invoking destructor, clearing up" << end;
if(buffer != NULL)
delete [] buffer;
}

int GetLength()
{
return strlen(buffer);
}

const char* GetString()
{
return buffer;
}
};

int main()
{
MyString sayHello("Hello from String class");
cout << "String buffer in sayHello is "<< sayHello.GetLength();
cout << " characters long"<< endl;

cout << "buffer contains: "<< sayHello.GetString()<<endl;
}

In this program, you don’t need andin you main function, they are hidden in the String class.

  • Pay attention: Destructor couldn’t be overloaded. If you forget Destructor, compiler will create a dummy destructor and invoke it, but dummy destructor is NULL, which means it can’t release the memory allocated dynamically.
Share