I'm new to C++ and I was asked a question that I really can't answer: when is the best time to overload or define your own copy constructor in C++?
Asked
Active
Viewed 103 times
0
-
The purpose of the copy-constructor is to create a copy of your object. If the default copy-constructor does not correctly create a copy then you should either disable it, or write your own one that does correctly create a copy. If you never need to copy your object, you can disable it. – M.M Jul 16 '14 at 09:16
-
It is also necessary when you manage resources that require special handling when copying/sharing. Some background information: http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) and http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization – Enigma Jul 16 '14 at 09:17
1 Answers
0
If your Instance need deep copy, then your have to define the copy constructor. Copy constructor does only the shallow copy. As example if your class has a char pointer.
See this code example.
#include <iostream>
using namespace std;
class Student
{
public:
char * m_name;
int m_age;
Student(char* name, int age){
int name_len = strlen(name)+1;
m_name= new char[name_len];
strncpy(m_name, name, name_len);
m_age = age;
}
};
int main()
{
char* firstStudent = "Kevin stefan";
Student kevin(firstStudent,1);
Student jhon = kevin;
char* secondStudent = "Jhon Mac";
strncpy(jhon.m_name,secondStudent,strlen(secondStudent));
cout << kevin.m_name << endl;
system("pause");
return 0;
}
The result of this program prints Jhon Macefan
. because both Student instance pointing to same memory location because of the shallow copy.
In this kind of situation you have to define a copy constructor
for deep copy like this
Student::Student(const Student& stu)
{
int name_len = strlen(stu.m_name);
m_name = new char[name_len+1];
strncpy(m_name, stu.m_name, name_len);
m_age = stu.m_age;
}

Nayana Adassuriya
- 23,596
- 30
- 104
- 147
-
I think this answer will only end up confusing people, even though your example is valid. As a counterexample, if the instance contains a `vector
`, then I (and I suspect, most) would call what the default copy constructor does a deep copy. – Jul 16 '14 at 09:18 -
1C++ does not really have "deep copy" and "shallow copy". Either the copy does what you want or it doesn't. So-called "shallow copy" could be correct if the resource being pointed to is not meant to be deleted by the class. – M.M Jul 16 '14 at 09:19
-
@MattMcNabb That's one thing that this answer does cover correctly: "If your Instance need deep copy" -- it already acknowledges that there are classes that don't need it. – Jul 16 '14 at 09:21