The first project
that many C++ books discuss in varying details is the development of a
character string class. One of C's primary shortcomings is that it lacks
the sophisticated string handling capability. Strings are pretty useful
since nearly every program manipulates text data of one type or another.
Developing a string class was one of my first C++ projects. I kept on
making changes in it as my understanding of C++ grew. Now, I think I am
satisfied with its performance hence I have decided to present it. Even
though some readers may not find it useful still I think concepts like
this pointer, overloaded assignment operator, copy constructor etc. get
clarified in developing the string class. The definition of the String
class begins with the definition of three private variables: size, len
and ptr. size contains the currently allocated length of the
ptr pointer. len holds the actual number of characters
stored in the string. The char pointer ptr points to the
location on the heap of the buffer containing the string's text data.
There are lot of member functions which help you access and manipulate
string objects. In general, class member functions are made public to
facilitate their use by user-defined objects.
# include "iostream.h" # include "limits.h" # include "string.h" # include "iomanip.h"
const chunk_size = 8 ; // allocation unit for strings class string { private: char *ptr ; // pointer to allocated space unsigned int len ; // current length of string unsigned int size ; // number of bytes allocated public : // constructors string() ; // zero argument constructor string ( char * ) ; // one argument constructor string ( char, unsigned int ) ; // two argument constructor string ( const string& ) ; // copy constructor