Hi everybody,
I'm having a really hard time learning about copy constructor. I have tried to read several books about copy constructor but seems like i'm stuck or something.
For example: (the code is pulled out from the book. The book fails to explain it more specifically)
Code:
#include <iostream>
#include <string>
using namespace std;
class my_string {
public:
my_string(): len(0)
{ s = new char[1]; assert(s != 0); s[0] = 0; }
my_string(const my_string& str);
my_string(const char* p);
~my_string() {delete []s; }
void assign(const my_string& str);
void print() const { cout << s << endl; }
void concat(const my_string& a, const my_string& b);
private:
char* s;
int len;
};
my_string::my_string(const char* p)
{
len = strlen(p);
s = new char[len + 1];
assert(s != 0);
strcpy(s, p);
}
my_string::my_string(const my_string& str) : len(str.len)
{
s = new char[len + 1];
assert(s != 0);
strcpy(s, str.s);
}
void my_string::assign(const my_string& str)
{
if (this == &str)
return;
delete []s;
len = str.len;
s = new char[len + 1];
assert(s != 0);
strcpy(s, str.s);
}
void my_string::concat(const my_string& a, const my_string& b)
{
char* temp = new char[a.len + b.len + 1];
len = a.len + b.len;
strcpy(temp, a.s);
strcat(temp, b.s);
delete []s;
s = new char[len + 1];
assert(s != 0);
strcpy(s, temp);
}
Ok! my question is let's say for this part of code:
Code:
my_string::my_string(const my_string& str) : len(str.len)
{
s = new char[len + 1];
assert(s != 0);
strcpy(s, str.s);
}
what does the "str" variable mean? is it an object that behaves exactly as my_string?
again, for "len(str.len)", I don't get this part. What does it do? (set length equal to the length of the object str?)
Another question i wanna ask is:
Code:
my_string(const my_string& str);
Code:
void assign(const my_string& str);
are both of these prototypes a copy constructor? the second one is not a constructor, but it has the same argument "(const my_string& str)". It really confuses me.