I'm trying to understand Deep Copy and write this program.
#include <iostream>
#include <string.h>
using namespace std;
char a[10];
class String
{
public:
char *ptr;
String()
{
ptr = a;
}
void setString(const char *str)
{
strcpy(ptr,str);
}
void operator=(String k){
ptr = new char[10];
strcpy(ptr, k.ptr);
}
char* getString()
{
return ptr;
}
};
class student
{
public:
String name;
student(){ }
student (const student &O){
name=O.name;
}
};
int main(){
student obj;
obj.name.setString("ABC");
student obj1=obj;
obj1.name.setString("NEW");
cout << obj.name.getString() << endl;
cout << obj1.name.getString() << endl;
}
It's working fine. But I'm trying to call Destructor to free the memory and when I write Destructor
then program not run properly.
~String(){
delete ptr;
}
I know it's could be due to ptr = a;
I already tested with other short examples and ptr=a caused the problem when Destructor
called.
- Is everything fine instead of Destructor?
- How I can free the memory?
Note: This Program is just to understand the Deep copy.