|
|
A second example using constructorsand destructors
Dynamic storage allocation and deallocation is a place
where constructors and destructors are useful. Consider
the case where we want to create a genuine String datatype
(class), which retains the string length data member.
A String object could contain strings of arbitrary length,
instead of being held in some fixed size array.
The String length could be kept, thus reducing use of the
strlen()function, which searches the entire string for the
terminating NULL character.
We can add special string manipulation operators, instead of
being restricted to what <string.h>supplies.
Let us assume that string objects can be declared as:
String S1("abc"), S2("pqrs");// C++
String S1 = "abc", S2 = "pqrs";// The C++ case is more general
// C
Anyway, we want S1 and S2 to have these values initially,
but to be changed later. Clearly our String class is going to
need a member function (constructor operator) which
allocates space to our strings and initializes them
appropriately:
class String {
String (const char* s); // constructor prototype
......
private:
char* text;// pointer to a string
int len;// length of string
};
|
|