1 2 3 4 5 6 7 8 9 10 11 12

Our constructor function could be defined as: String :: String (const char* s)
{
len = strlen(s);
text = new char[len+1];

}strcpy(text, s);

after computing the length of the string that s points to, the constructor uses it to allocate enough space for a copy of a string, before finally moving it into place.
To give back the space we need a
destructor. If we don't have one, then consider the problems of using the String class within a procedure

void procedure ()
{
String S1("abc");

}........

when procedureis called the object S1 is created by the constructor, but when the procedure returns the fields textand lenofS1are removed, but the string "abc" itself (that textpoints to) remains. This failure to return all the memory acquired during procedure execution is called a memory leak.
A destructor, a function that is called automatically when an object ceases to exist, saves the day. Constructors and destructors are matched pairs. Thus a destructor is a member function just like a constructor and has the same name, but with a
tilde (~)pre-pended.

For example:

March 11, 1998

Page 5

C201/TAM