Say you have the class
class MyString {
public:
MyString() {
m_szTheString = NULL;
}
MyString(const char *szString) {
size_t nLen = strlen(szString) + 1;
m_szTheString = new char[nLen];
memcpy(m_szTheString, szString, nLen);
}
~MyString() {
if (m_szTheString != NULL) {
delete []m_szTheString;
}
}
private:
char *m_szTheString;
};
This is using the default copy constructor.
if we look at this class in memory, it takes 4 (or 8 on 64 bit) bytes of memory, to store the pointer to the string held in
m_szTheString
.
Then the default copy constructor does what is called a "shallow copy", that is copy the memory from 1 instance to the other. Think of it like this:
MyString strA("hello");
MyString strB(strA);
is (conceptually) equivelent to
MyString strA("hello");
MyString strB();
memcpy(&strB, &strA, sizeof(MyString));
This means that both classes now have a pointer to the same memory address (the actual string), so if 1 of the objects changes the string, then it changes in the other 1 too.
By using your own copy constructor you can make a copy of the memory referanced too.
MyString(const MyString &strOther) {
size_t nLen = strlen(strOther.m_szTheString) + 1;
m_szTheString = new char[nLen];
memcpy(m_szTheString, szString, nLen);
}