Question on Copy Constructor

Can someone verify my code for copy constructor and assigment operator?
Having a problem with delete in the destructor,I assume I am going wrong somewhere,Can some one highlight the problem.

-----------------------------------------------------------------------------
class hello
{
char *name;
public:
hello(char *s)
{
name = new char[10];
strcpy(name,s);
cout<<"Default constructor.\n";
}
hello(const hello &h)
{
name = new char[10];
strcpy(name,h.name);
cout<<"In the copy constructor.\n";
cout<<" the name is "<<name;
}
hello &operator = (const hello &i)
{
name = i.name;
cout<<"In assignment operator"<<endl;
cout<<"Name is "<<name<<"\n";
return *this;
}
~hello()
{
//delete name;
cout<<"In the destructor/n";
}

};
int main()
{
hello h("Welcome");
hello g = h;
hello p("Application");
p = h;
return 0;
}

1
2
3
4
hello(const hello &h)
{
name = new char[10];
strcpy(name,h.name);
This is ok, deep copy

1
2
3
hello &operator = (const hello &i)
{
name = i.name;
This will crash when destructor called (shallow copy -> pointer only)


EDIT: you should take the size from the paremeter (i.e. strlen())
Last edited on
So is this the right way.This works anyways...

hello &operator = (const hello &i)
{
if(this != &i)
{
delete[] name;
name = new char(strlen(i.name)+ 1);
strcpy(name , i.name);
cout<<"In assignment operator"<<endl;
cout<<"Name is "<<name<<"\n";
}
return *this;
}
Topic archived. No new replies allowed.