A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).
Person q("Mickey"); // constructor is used to build q.
Person r(p); // copy constructor is used to build r.
Person p = q; // copy constructor is used to initialize in declaration.
p = q; // Assignment operator, no constructor or copy constructor.
f(p); // copy constructor initializes formal value parameter.
C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes a shallow copy.
Copy constructors are required for classed having POINTERS , FILEHANDLES and OTHER RESOURCES
class Person {
private:
int age;
char * name;
public: // the following three member functions must be defined by the class implementer
Person (const char * name, int age);
Person (const Person& other);
};
int a = 10;
int b = 5;
int * pa = &a;
int * pb = &b;
cout << "pa = " << pa << "\n";
cout << "pb = " << pb << "\n";
cout << "a = " << *pa << "\n";
cout << "b = " << *pb << "\n";
pb = pa;
cout << "After pb = pa \n\n";
cout << "pa = " << pa << "\n";
cout << "pb = " << pb << "\n";
cout << "a = " << *pa << "\n";
cout << "b = " << *pb << "\n";
char a[] = "a\0";
char b[] = "b\0";
char * pa = a;
char * pb = b;
cout << "pa = " << &pa << "\n";
cout << "pb = " << &pb << "\n";
cout << "a = " << pa << "\n";
cout << "b = " << pb << "\n";
//strcpy(pb,pa);
pb = pa;
cout << "After pb = pa \n\n";
cout << "pa = " << &pa << "\n";
cout << "pb = " << &pb << "\n";
cout << "a = " << pa << "\n";
cout << "b = " << pb << "\n";