Importance of copy constructor

String class in C++ Without copy constructor

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
char *s;
int size;
public:
String( char *str = NULL); // constructor
void print() { cout << s << endl; }
void change(const char *); // Function to change
};

String::String( char *str)
{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

void String::change(const char *str)
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

int main()
{
String str1("mice");
String str2 = str1;

str1.print(); // what is printed ?   mice
str2.print(); // what is printed ?   mice

str2.change("Udupi");

str1.print(); // what is printed now ? Udupi
str2.print(); // what is printed now ? Udupi
return 0;
}

String class in C++ With copy constructor

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
char *s;
int size;
public:
String( char *str = NULL); // constructor
String( String &ss);  //copy constructor
~String() { delete [] s; }// destructor
void print() { cout << s << endl; }
void change(const char *); // Function to change
};
String::String( String &ss)  
{
    size = strlen(ss.s);
s = new char[size+1];
strcpy(s, ss.s);
}
String::String( char *str)
{
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

void String::change(const char *str)
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}

int main()
{
String str1("mice");
String str2 = str1;

str1.print(); // what is printed ?   mice
str2.print(); // what is printed ?   mice

str2.change("Udupi");

str1.print(); // what is printed now ? mice
str2.print(); // what is printed now ? Udupi
return 0;
}

Comments

Post a Comment