#include <stdio.h>
#include <string.h>

class Str {
    char *s;
    static char *Join(const char *a, const char *b);
public:
    Str(const char *a = "");                /* default + conversion */
    Str(const Str &o);                      /* copy constructor */
    ~Str() { delete[] s; }
    const Str &operator=(const Str &o);     /* assignment: Str = Str */
    const Str &operator=(const char *a);    /* assignment: Str = "..." */
    const Str &operator+=(const Str &o);    /* compound assignment */
    const char *Get() const { return s; }
};

/* new buffer holding a followed by b */
char *Str::Join(const char *a, const char *b)
{
    char *r = new char[strlen(a) + strlen(b) + 1];

    strcpy(r, a);
    strcat(r, b);
    return r;
}

Str::Str(const char *a)
{
    printf("  Str(const char *)\n");
    s = Join(a, "");
}

Str::Str(const Str &o)                      /* *this is new: s is garbage */
{
    printf("  Str(const Str &)          copy constructor\n");
    s = Join(o.s, "");                      /* just build */
}

const Str &Str::operator=(const Str &o)     /* *this exists: s is a buffer */
{
    printf("  operator=(const Str &)\n");
    char *n = Join(o.s, "");                /* build the new one first, */
    delete[] s;                             /* then drop the old one: */
    s = n;                                  /* safe even for a = a */
    return *this;
}

const Str &Str::operator=(const char *a)
{
    printf("  operator=(const char *)\n");
    char *n = Join(a, "");
    delete[] s;
    s = n;
    return *this;
}

const Str &Str::operator+=(const Str &o)
{
    printf("  operator+=(const Str &)\n");
    char *n = Join(s, o.s);                 /* safe even for a += a */
    delete[] s;
    s = n;
    return *this;
}

int main()
{
    printf("Str a(\"hello\");\n");  Str a("hello");
    printf("Str b = a;\n");         Str b = a;
    printf("Str c(a);\n");          Str c(a);
    printf("Str d;\n");             Str d;
    printf("d = a;\n");             d = a;
    printf("d = \"world\";\n");     d = "world";
    printf("d += a;\n");            d += a;
    printf("a = a; a += a;\n");     a = a; a += a;

    printf("a=%s b=%s c=%s d=%s\n", a.Get(), b.Get(), c.Get(), d.Get());
    return 0;
}
