//This is the implementation of the class StringVar. #include #include #include #include #include "StringVar.h" using namespace std; // Constructor that takes an int size StringVar::StringVar(int size) : max_length(size) { value = new char[max_length + 1];//+1 is for '\0'. value[0] = '\0'; } // Default constructor StringVar::StringVar( ) : max_length(100) { value = new char[max_length + 1];//+1 is for '\0'. value[0] = '\0'; } // Constructor that takes a cstring - Uses cstring StringVar::StringVar(const char a[]) : max_length(strlen(a)) { value = new char[max_length + 1];//+1 is for '\0'. strcpy(value, a); } // Copy constructor - Uses cstring StringVar::StringVar(const StringVar& string_object) : max_length(string_object.length( )) { value = new char[max_length + 1];//+1 is for '\0'. strcpy(value, string_object.value); cout <<"copy construcor called " << string_object << endl; } // Overloaded operator= creates a deep copy of the object and // returns a reference to it. StringVar & StringVar::operator= (const StringVar & right) { //THis handles the case when left and right hand of assignment operator //are the same... cout <<"copy assignment called"; if (this == &right) { cout << ":" << right << endl; return *this; } // If there is not enough capacity for the value, grow it. if (max_length < strlen(right.value)) { cout <<" resizing," ; //need to free the old space and allocate new space delete [] value; max_length = strlen(right.value); value = new char[max_length+1]; } // Need to copy the value so that they are the same. cout <<" copying: " << right << endl; strcpy (value,right.value); return *this; } // Destructor cleans up dynamic memory. StringVar::~StringVar( ) { delete [] value; } // Uses cstring: int StringVar::length( ) const { return strlen(value); } //Uses iostream: istream& operator>> (istream& ins, StringVar& the_string) { // This is used to avoid buffer overflow given a fixed buffer // length. No dynamic growth. This also reads in white space // but not newlines. ins.getline(the_string.value, the_string.max_length + 1); return ins; } //Uses iostream: ostream& operator<< (ostream& outs, const StringVar& the_string) { outs << the_string.value; return outs; }