I\'m trying to write my own C++ String class for educational and need purposes.
The first thing is that I don\'t know that much about operators and that\'s why I want to
A few mistakes you made:
1. Copy constructor signature is wrong. It must be:
CString(const CString& q)
2. op= signature is wrong. It must be:
CString& operator=(const CString& q)
Btw., that was also the reason that the copy constructor was called. You did a return *this
in the end which copied the object (with your op= signature).
3. You allow CString instances with cstr == NULL
(your default constructor will result in such an instance). Though, in almost all functions (copy constructor, operator +
, operator =
) you don't handle that case well (q.cstr == NULL
).
Maybe the easiest and safest way would be to just disallow that case and change your default constructor to:
CString::CString()
{
cstr = new char[1];
cstr[0] = 0;
}