Listing 5 Implementation for Listing 4

// str.cpp

#include <iostream. h>
#include <string.h>
#include "str.h"

String::String(const char *buf)
{
    if (!buf)
        rep = new Srep("");
    else
        rep = new Srep(buf);
}

String::String(const String& s)
{
    rep = s.rep;
    rep->count++;
}

String::~String()
{
    if (--rep->count <= 0)
        delete rep;
}

String::Srep::Srep(const char* s)
{
    strcpy(rep = new char[strlen(s)+1], s);
    count = 1;
}

String::Srep::~Srep()
{
    delete [] rep;
}
// End of File