Write your question here.
Why in some cases len is calculated using
1. len = strlen(str) + 1;
2. len = strlen(obj.p) + 1;
3. len = obj.len;
4. len = obj.len + 1;
For example 1, I think it is because a literal string is the parameter for the constructor, and hence, the plus 1 is for the '\0' to make it a character string.
For example 2, I don't know the reason for the plus 1. The object being copied should already have the '\0' at the end.
For example 3, I see this as being correct as the existing object should have the '\0' at the end.
For example 4, I don't know the reason for the plus 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
CBadClass obj("Test it!");
obj.showIt();
CBadClass obj1("Hello World!");
obj1.showIt();
// Use Assignment Operator
obj = obj1;
obj.showIt();
// Use Copy Constructor
obj = "Second test it!";
CBadClass obj2(obj);
obj2.showIt();
}
For c-string there are two distinct lengths:
1) length of string itself. It can be calculated by calling a strlen()
2) Length of memory block required to store string. This is always 1 more than string length to accomodate for trailing 0.
In your code copy assigment operator is incorrect: len member is not a length of string, but size of memory block, and you do not need to add 1 to it.
So, for the Assignment operator, len should be obj.len; and not obj.len + 1;
Similarly, for the Copy constructor, len should also be obj.len; and not strlen(str) + 1; since the object being copied has a len member, the size of the memory block.