In: Computer Science
What problems could a programmer encounter if they defined a destructor for a class but no copy constructor? Illustrate your description with an example class.
Programming language: C++
Requirement: provide answer along with one code example with illustration.
If we do not have copy constructor in the program, we don’t get the expected output.
In the Code below Without Copy constructor .The changes made to str2 reflect in str1 as well which is never expected.
This is because if we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. The compiler created copy constructor works fine in general But Default constructor does only shallow copy.
Here is code without Copy Constructor.
#include<iostream>
#include<cstring>
using namespace std;
class MyClass
{
private:
char *s;
int size;
public:
MyClass(const char *str = NULL) // constructor
{
size =
strlen(str);
s = new
char[size+1];
strcpy(s,
str);
}
~MyClass() // destructor
{
delete [] s;
}
void print()
{ cout << s << endl;
}
void change(const char * str) // Function to
change
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
};
int main()
{
MyClass str1("String 1");
MyClass str2 = str1;
str1.print(); // what is printed
?
str2.print();
str2.change("String 2 Change");
str1.print(); // what is printed now
?
str2.print();
return 0;
}
Now the code with Copy Constructor:
#include<iostream>
#include<cstring>
using namespace std;
class MyClass
{
private:
char *s;
int size;
public:
MyClass(const char *str = NULL) // constructor
{
size =
strlen(str);
s = new
char[size+1];
strcpy(s,
str);
}
MyClass(const MyClass& old_str) //Copy constructor
{
size = old_str.size;
s = new char[size+1];
strcpy(s, old_str.s);
}
~MyClass() // destructor
{
delete [] s;
}
void print()
{ cout << s << endl;
}
void change(const char * str) // Function to
change
{
delete [] s;
size = strlen(str);
s = new char[size+1];
strcpy(s, str);
}
};
int main()
{
MyClass str1("String 1");
MyClass str2 = str1;
str1.print(); // what is printed ?
str2.print();
str2.change("String 2 Change");
str1.print(); // what is printed now
?
str2.print();
return 0;
}
See the difference here changes only made for str2 Object not
with str1 this is because Our Copy Constructor has created a deep
copy of str1 String in str2.SO If there is some changes with any
object It will Reflect the changes only for that object not for all
others.