I am creating a class that works similar to the string class. I am in a starting stage doing some experiments.
Assume all header files are added
class String
{
public:
int len;
char *str = NULL;
// Default constructor
String()
{
len = 0;
str = new char[1];
str[0] = '\0';
printf("New memory: %p\n", str);
}
// Copy constructor
String(const char *ch)
{
len = strlen(ch);
if (str != NULL)
{
printf("Old memory: %p\n", str);
delete str;
printf("Deleted...\n");
}
str = new char[len + 1];
printf("New memory: %p\n", str);
for (int i = 0; i <= len; i++)
str[i] = ch[i];
}
};
int main()
{
String msg;
std::cout << msg.len << std::endl;
std::cout << msg.str << std::endl;
msg = "Hello";
std::cout << msg.len << std::endl;
std::cout << msg.str << std::endl;
}
When I create a String object 1 byte of memory is allocated to store string and initialises with \0
on line String msg;
When copy constructor is called on line msg = "Hello";
it first checks for any previous allocation of memory and to avoid memory wastage it will delete
that and recreates a new memory block.
The issue is when copy constructor
is called line if (str != NULL)
is not getting executed. It should execute because str
is allocated a byte of memory earlier in default constructor
and it is not NULL.
What may be the thing that I missed out?