Self copy constructor

Hi,
When I was doing some code practice and found below behavior.

issue:When I create constructor and assign self copy constructor than program
crash.
sample d("abhishek");
sample e=e;

If I comment the first line and write only sample e=e than I did not find
any issue and it call the copy constructor.

Can anyone provide some idea.

#include<iostream>
#include<string.h>

using namespace std;

class sample
{
public:
char *p;
sample(const char *p_s=" ");
sample(sample &s);
sample& operator=(sample &s);
};

sample::sample(const char *p_s)
{

int len= strlen(p_s)+1;
if(len==2)
{
cout<<"Passed empty string"<<endl<<endl;
return;
}
p = new char[len];
strncpy(p,p_s,len);
p[len-1]='\0';
cout<<"Default Constructor :"<<p<<endl;
}

sample::sample(sample &s)
{
cout<<"Copy Constructor called 1"<<endl;
int len =strlen(s.p)+1;
cout<<"Copy Constructor called 2"<<endl;
p = new char[len];
cout<<"Copy Constructor called 3"<<endl;
strncpy(p,s.p,len);
p[len-1]='\0';
cout<<"Copy Constructor"<<p<<endl;

};

sample& sample::operator=(sample &s)
{
if(this==&s)
return *this;
else
{
int len=strlen(s.p)+1;
p=new char[len+1];
strncpy(p,s.p,len);
p[len-1]='\0';
cout<<"Assignment operator :"<<p<<endl;
return *this;
}
}

int main()
{
sample d("abhishek");
sample e=e;
cout<<"Self Copy Constructor Value"<<e.p<<endl;
sample f,g;
g=f=d;

return 0;
}

It does not even compile for me, it says that e does not exist (because it hasn't even been created yet?)
It compiles for me, but I think it is undefined behaviour.
> It compiles for me, but I think it is undefined behaviour.

+1

sample e=e; e is being used before it is initialized.
it is compiled for me.

if I comment this line.
sample d("abhishek");


than I got following output.


Copy Constructor called 1
Copy Constructor called 2
Copy Constructor called 3
Copy Constructor
Self Copy Constructor Value
Passed empty string

Passed empty string
gcc compiler.

Add comment remove d from assignment line also as we have comment above.(just fyi for compilation)
Topic archived. No new replies allowed.