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
Here's what's going on:
CString a = [CString result of operator +]
, c++ will just call you're copy constructor. Hence the call to CString(CString& )
that you're seeing in the debugger.Now, that's 4 total objects just created, one for each string literal ("hello", and " world"), one for the concatenation of those (the result of the CString::operator +
call, and one to hold the result (CString a = ...
). Each one of those temporary objects will have it's destructor called.
As for why you're not getting the printf, I have no idea. I just copy pasted your code in this file:
#include <cstdio>
#include <cstring>
[your code]
int main(int argc,char* argv[]) {
CString a = CString("hello") + CString(" world");
printf(a);
}
And when I ran the resulting executable, I got hello world
as the output. This is on Ubuntu with g++ 4.4. Not exactly sure why under the VS debugger it's not printing anything.
The line:
cstr=new char[strlen(str)];
should be:
cstr=new char[strlen(str) + 1];
Also, the test for self-assignment does not make sense in the copy constructor - you are creating a new object - it cannot possibly have the same address as any existing object. And the copy constructor should take a const reference as a parameter,
If in your code, you were expecting the assignment operator to be used, you would be expectining wrong. This code:
CString a = CString("Hello") + CString(" World");
is essentially the same as:
CString a( CString("Hello") + CString(" World") );
which is copy construction, not assignment. The temporary CString "Hello world" will be destroyed (invoking the destructor) after a has been constructed.
Basically, it sounds as if your code is working more or less as expected.
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;
}
Don't use strlen, store your own string length. The string should not be depended on to have a null terminator. It's ok to use such if you're passed in a random const char*, but for internal operations, you should use the size.
Also, you forgot to make your operator const char* a const overload.