References, Constness, and Copy Constructors

I made a mistake in class when I said that C++ uses the copy constructor for the case obj1 = obj2. It does not. You have to explicitly overload the assignment operator. We will discuss this in the next class.

#include <cstdio>
#include <cstring>

class SillyString
{
public:
    SillyString();
    SillyString(const char *str);
    SillyString(const SillyString& other);
    ~SillyString();

    SillyString& operator = (const SillyString& other);

    size_t length() const;
    const char *c_str() const;

private:
    char *data;
};

SillyString::SillyString()
{
    data = NULL;
}

const char *
SillyString::c_str() const
{
    if (data == NULL) {
        return "";
    } else {
        return data;
    }
}

size_t
SillyString::length() const
{
    return strlen(data);
}

SillyString::SillyString(const char *str)
{
    if (str == NULL) {
        data = NULL;
    } else {
        size_t len = strlen(str);
        data = new char[len + 1];
        strcpy(data, str);
    }
}

SillyString::SillyString(const SillyString& other)
{
    if (other.data == NULL) {
        data = NULL;
    } else {
        size_t len = other.length();
        data = new char[len + 1];
        strcpy(data, other.data);
    }
}

SillyString&
SillyString::operator = (const SillyString& other)
{
    delete[] data;

    if (other.data == NULL) {
        data = NULL;
    } else {
        size_t len = other.length();
        data = new char[len + 1];
        strcpy(data, other.data);
    }

    return *this;
}

SillyString::~SillyString()
{
    delete[] data;
}

int
main()
{
    SillyString *str = new SillyString("Hi, my name is Faith");
    SillyString str2(*str);
    delete str;
    str2 = "No it isn't";

    printf("%s.\n", str2.c_str());

    return 0;
}