title: Custom string class (C++)
body: <p>I'm trying to write my own C++ String class for educational and need purposes.<br>
  The first thing is that I don't know that much about operators and that's why I want to learn them.
  I started writing my class but when I run it it blocks the program but does not do any crash.<br>
  Take a look at the following code please before reading further:  </p>
  
  <pre><code>class CString
  {
  private:
    char* cstr;
  public:
    CString();
    CString(char* str);
    CString(CString&amp; str);
    ~CString();
  
    operator char*();
    operator const char*();
    CString operator+(const CString&amp; q)const;
       CString operator=(const CString&amp; q);
  };
  </code></pre>
  
  <p>First of all I'm not so sure I declared everything right. I tried googleing about it but all the tutorials about overloading explain the basic ideea which is very simple but lack to explain how and when each thing is called. For instance in my = operator the program calls CString(CString&amp; str); but I have no ideea why.<br>
  I have also attached the cpp file below:</p>
  
  <pre><code>CString::CString()
  {
   cstr=0;
  }
  CString::CString(char *str)
  {
   cstr=new char[strlen(str)];
   strcpy(cstr,str);
  }
  CString::CString(CString&amp; q)
  {
   if(this==&amp;q)
    return;
   cstr = new char[strlen(q.cstr)+1];
   strcpy(cstr,q.cstr);
  }
  CString::~CString()
  {
   if(cstr)
    delete[] cstr;
  }
  CString::operator char*()
  {
   return cstr;
  }
  CString::operator const char* ()
  {
   return cstr;
  }
  CString CString::operator +(const CString &amp;q) const
  {
   CString s;
   s.cstr = new char[strlen(cstr)+strlen(q.cstr)+1];
   strcpy(s.cstr,cstr);
   strcat(s.cstr,q.cstr);
   return s;
  }
  CString CString::operator =(const CString &amp;q)
  {
   if(this!=&amp;q)
   {
    if(cstr)
     delete[] cstr;
    cstr = new char[strlen(q.cstr)+1];
    strcpy(cstr,q.cstr);
   }
   return *this;
  }
  </code></pre>
  
  <p>For testing I used a code just as simple as this<br>
  CString a = CString("Hello") + CString(" World");<br>
  printf(a);<br>
  I tried debugging it but at a point I get lost. First it calls the constructor 2 times for "hello" and for " world". Then it get's in the + operator which is fine. Then it calls the constructor for the empty string. After that it get's into "CString(CString&amp; str)" and now I'm lost. Why is this happening? After this I noticed my string containing "Hello World" is in the destructor (a few times in a row). Again I'm very puzzeled. After converting again from char* to Cstring and back and forth it stops. It never get's into the = operator but neither does it go further. printf(a) is never reached.<br>
  I use VisualStudio 2010 for this but it's basically just standard c++ code and thus I don't think it should make that much of a difference</p>