I have copied this code from a site. But I am having problems understanding it properly. Please can you help me these doubts. I have written them as comments.
#include<iostream>
using namespace std;
#include<cstring>
class strings
{
char *m_string;
int m_length;
public:
strings(const char* str = "")
{
m_length = strlen(str) + 1;
m_string = new char[m_length];
strncpy(m_string,str,m_length);
m_string[m_length - 1] = '\0';/*1*/
}
~strings() /*2*/
{
delete[] m_string;
m_string = 0;/*3*/
}
char* get()
{
return m_string;
}
};
int main()
{
strings cstring("Alex");
cout << "Hi I am " << cstring.get();
cout << "\nsup";
strings cstrings1("Shady");
cout << "\nyo " << cstrings1.get();
return 0;
}
- why is the code asking me to do this. When I removed this line code still worked perfectly fine
- why are they using the destructor? Again not using it does seem to have any effect on the program
- Also what is the use of doing this when I just used the delete keyword
Can you guys please explain to me in easy way really what do I use a destructor for? Thank you so much