Shallow Copy and Deep Copy Example

Define string class with dynamic memory allocation for string. Define default constructor, parameterized constructors, copy constructor, destructor, Overload +, [], =, <<, >> operators. Observe the behavior of shallow copying and deep copying.

#include<iostream>
using namespace std;
#include<string.h>

class cstring
{

char *sptr;
int length;

public:

cstring()
{
sptr=NULL;
length=0;
}

cstring(const char *s)
{
sptr=new char[strlen(s)+1];
strcpy(sptr,s);
length=strlen(s);
}

cstring(const cstring &s)
{

sptr=new char[s.length+1];
strcpy(sptr,s.sptr);
length=s.length;
}

void print_cstring()
{
cout<<sptr<<endl;
}
void scan_cstring()
{
sptr=new char[10];
cin>>sptr;
}


~cstring()
{
if(sptr!=NULL)
delete []sptr;
}

cstring operator=(cstring c)
{
delete []sptr;
sptr=new char[strlen(c.sptr)+1];
strcpy(sptr,c.sptr);
length=c.length;
return (*this);
}


cstring operator+(cstring &c)
{

cstring temp;
temp.length=length+c.length;
temp.sptr=new char [temp.length+1];
strcpy(temp.sptr,sptr);
strcat(temp.sptr,c.sptr);
return temp;
}
char  operator[](int index)
{
if(index>=length)
cout<<"\n invalid arguments";
return (sptr[index]);
}
friend ostream& operator<<(ostream &cout,const cstring &c);
friend istream& operator>>(istream &cin,cstring &c);
};


ostream& operator<<(ostream &cout,const cstring &c)
{
cout<<c.sptr;
return cout;
}
istream& operator>>(istream &cin,cstring &c)
{
char buffer[100];
cin>>buffer;
c.sptr=new char[strlen(buffer)+1];
c.length=strlen(buffer);
strcpy(c.sptr,buffer);
//cin>>c.sptr;
return cin;
}
int main()
{


cstring s1,s2("jamal"),s3(s2),s4("manish"),s5;

s2.print_cstring();
s3.print_cstring();
//s4=s3;
s4.print_cstring();
s5=s3+s4;
s5.print_cstring();
cout<<s5;
//s1.scan_cstring();
cin>>s1;
cout<<s1;
cout<<endl<<s2[3];
return 0;
}




Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig