using namespace std;
class Cstring
{
public:
char *sptr;
int len;
public:
Cstring()
{
cout<<"inside default"<<endl;
sptr=NULL;
len=0;
}
Cstring(char *p)
{
cout<<"inside parameterized"<<endl;
len=strlen(p);
sptr=new char[len+1];
strcpy(sptr,p);
}
Cstring(const Cstring &s1)
{
cout<<"inside copy constructor"<<endl;
sptr=s1.sptr;
len=s1.len;
}
~Cstring()
{
cout<<"inside destructor"<<endl;
}
Cstring operator=(Cstring);
Cstring operator+(Cstring);
char& operator[](int index);
friend ostream& operator<<(ostream &,Cstring);
friend istream& operator>>(istream &,Cstring &);
};
istream& operator>>(istream &din,Cstring &c)
{
c.sptr=new char[20];
din>>c.sptr;
c.len=strlen(c.sptr);
}
ostream& operator<<(ostream &dout,Cstring c)
{
dout<<c.sptr;
dout<<c.len;
}
char& Cstring::operator[](int index)//overloading [] opertaor
{
return (sptr[index]);
}
Cstring Cstring::operator=(Cstring s1)//deep copying
{
if(sptr!=NULL)
delete sptr;
len=s1.len;
sptr=new char[len+1];
strcpy(sptr,s1.sptr);
}
Cstring Cstring::operator+(Cstring s2)//deep copying
{
int len1,len2;
Cstring temp;
len1=len;
len2=s2.len;
temp.sptr=new char[len1+len2+1];
temp.len=len1+len2+1;
strcpy(temp.sptr,sptr);
strcat(temp.sptr,s2.sptr);
return temp;
}
int main()
{
Cstring s1("grapes"),s2(s1),s3,s4,s5;
s3=s2;
cout<<s3.sptr<<endl;
s4=s1+s2;
cout<<"hi"<<s4.sptr<<" "<<s4.len<<endl;
s4[2]='p';
cout<<s4[0]<<endl;
cout<<s4.sptr<<endl;
cin>>s5;
cout<<s5;
return 0;
}
Comments