1) The destructor must have the same name as the class, preceded by a tilde (~).
2) The destructor can not take arguments.
3) The destructor has no return type.
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
| class MyString { private : char *m_pchString; int m_nLength; public : MyString( const char *pchString= "" ) { // Find the length of the string // Plus one character for a terminator m_nLength = strlen (pchString) + 1; // Allocate a buffer equal to this length m_pchString = new char [m_nLength]; // Copy the parameter into our internal buffer strncpy (m_pchString, pchString, m_nLength); // Make sure the string is terminated m_pchString[m_nLength-1] = '\0' ; } ~MyString() // destructor { // We need to deallocate our buffer delete [] m_pchString; // Set m_pchString to null just in case m_pchString = 0; } char * GetString() { return m_pchString; } int GetLength() { return m_nLength; } }; |
1
2
3
4
5
6
| int main() { MyString cMyName( "Alex" ); std::cout << "My name is: " << cMyName.GetString() << std::endl; return 0; } // cMyName destructor called here! |
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
| class Simple { private : int m_nID; public : Simple( int nID) { std::cout << "Constructing Simple " << nID<< std::endl; m_nID = nID; } ~Simple() { std::cout << "Destructing Simple" << m_nID << std::endl; } int GetID() { return m_nID; } }; int main() { // Allocate a Simple on the stack Simple cSimple(1); std::cout << cSimple.GetID() << std::endl; // Allocate a Simple dynamically Simple *pSimple = new Simple(2); std::cout << pSimple->GetID() << std::endl; delete pSimple; return 0; } // cSimple goes out of scope here |
0 comments: